Compare commits

...

499 Commits

Author SHA1 Message Date
grossmj
6670b0d362 Release v3.0.0a3 2022-12-27 15:22:16 +08:00
grossmj
59a89cc40b Catch timeout error while updating appliance files 2022-12-27 13:54:57 +08:00
grossmj
25e665ff2c Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/crash_report.py
#	gns3/version.py
#	requirements.txt
2022-12-27 13:26:46 +08:00
grossmj
617cf7ef02 Fix RecursionError with invalid credentials. Fixes #3374 2022-12-27 12:19:55 +08:00
grossmj
b4daafffad Allow raw images by default. Fixes https://github.com/GNS3/gns3-server/issues/2097 2022-12-26 11:28:51 +08:00
grossmj
6e7947eea3 Remove deprecated PuTTY option in preferences. Ref https://github.com/GNS3/gns3-gui/discussions/3415 2022-12-24 11:19:29 +08:00
grossmj
f329039987 Do not send empty EtherType when updating an Ethernet switch 2022-12-24 08:26:59 +08:00
grossmj
d43804374f Fix bad message for config file of HDPI. Fixes #3389 2022-12-22 19:12:40 +08:00
grossmj
f54a7f6096 Fix test_add_appliance_with_symbol_from_symbols_dir 2022-12-22 19:03:50 +08:00
grossmj
8a51d5edbe Fix some more tests on Windows 2022-12-22 18:57:02 +08:00
grossmj
2a845a1cf8 Fix more tests on Windows 2022-12-22 18:19:20 +08:00
grossmj
2e793f065a Try to fix tests on Windows 2022-12-22 17:00:19 +08:00
grossmj
0a69cced62 Fix tests 2022-12-22 16:13:35 +08:00
grossmj
320e8243ee Downgrade to flake8 v5.0.4 2022-12-22 09:46:11 +08:00
grossmj
37af40e594 Update dependencies 2022-12-22 09:42:14 +08:00
grossmj
669fee1877 Update GH actions checkout and setup-python 2022-12-22 09:35:46 +08:00
grossmj
833b9d00c9 Upgrade dependencies 2022-12-18 14:14:56 +08:00
grossmj
e68937475f Development on v2.2.36.dev2 2022-11-11 00:36:47 +08:00
grossmj
6f418f0853 Release v2.2.35.1 2022-11-10 22:21:14 +08:00
grossmj
8e59927ada Merge branch 'master' into 2.2 2022-11-10 22:06:25 +08:00
grossmj
db8155a818 Merge branch '2.2' into 3.0
# Conflicts:
#	CHANGELOG
#	dev-requirements.txt
#	gns3/crash_report.py
#	gns3/dialogs/edit_project_dialog.py
#	gns3/http_client.py
#	gns3/version.py
#	requirements.txt
#	win-requirements.txt
2022-11-09 20:14:39 +08:00
grossmj
1012686053 Development on 2.2.36.dev1 2022-11-09 20:02:20 +08:00
grossmj
672bd850ad Merge branch '2.2' 2022-11-09 20:00:38 +08:00
grossmj
5db5e1f9fe Release v2.2.35 2022-11-08 23:40:25 +08:00
grossmj
ca94c71bf2 Use Visual Studio 2022 in appveyor.yml 2022-11-08 23:09:23 +08:00
grossmj
76264c55ce Merge branch 'master' into 2.2 2022-11-08 19:29:49 +08:00
grossmj
fd243c42a8 Downgrade psutil to v5.9.2 2022-11-08 19:18:07 +08:00
grossmj
a6521ef9e4 Upgrade psutil to v5.9.4 2022-11-08 18:49:31 +08:00
grossmj
9fa833762c Upgrade pywin32 to v305 2022-11-08 18:29:51 +08:00
grossmj
ca0c6468b5 Fix "variables": [] in project file leads to unlimited increase of empty name/value pairs in GUI. Fixes #3397 2022-11-07 22:29:02 +08:00
grossmj
15f6945a94 Upgrade dependencies 2022-11-07 21:48:45 +08:00
grossmj
645deb8c79 Ignore local revision when comparing versions. 2022-11-07 20:03:05 +08:00
grossmj
428f12a2b3 Make version PEP 440 compliant 2022-11-06 17:51:31 +08:00
grossmj
9ad5760ee6 Support for Python 3.11 2022-10-30 19:04:54 +08:00
grossmj
82fc4fb3c9 Revert "Fix issue when using tail.exe with non-ascii paths. Fixes #3021"
This reverts commit df42147d92.
2022-10-19 19:38:43 +08:00
grossmj
df42147d92 Fix issue when using tail.exe with non-ascii paths. Fixes #3021 2022-10-19 19:04:29 +08:00
grossmj
da5520aa90 Upgrade PyQt to 5.15.7 and pywin32 to v304 2022-10-19 18:31:40 +08:00
grossmj
04d81efe92 Upgrade PyQt5 to v5.15.7 and pywin32 to v304 2022-10-19 18:30:03 +08:00
Jeremy Grossmann
491c66a315 Merge pull request #3395 from GNS3/fix/3393
Update requirements.txt
2022-10-18 22:30:11 +08:00
Jeremy Grossmann
e5c81da700 Merge branch '2.2' into fix/3393 2022-10-18 22:28:32 +08:00
grossmj
65fad1b4f4 Upgrade to Visual Studio 2022 in appveyor.yml 2022-10-18 21:47:10 +08:00
grossmj
34661908d9 Upgrade to Python 3.7 in appveyor.yml 2022-10-18 21:42:51 +08:00
grossmj
aee5ffa17f Upgrade pip and setuptools in appveyor.yml 2022-10-18 21:40:08 +08:00
grossmj
e9e8be42b5 Upgrade pytest. Fixes #3399 2022-10-18 21:16:46 +08:00
grossmj
ae0d928383 Use jsonschema v3.2.0 for Python 3.6 2022-10-12 22:13:34 +08:00
grossmj
8db3c1be42 Allow for more dependency versions at patch level 2022-10-12 22:07:37 +08:00
grossmj
f50da3ebd7 Replace deprecated distro.linux_distribution() call 2022-10-11 23:28:11 +08:00
grossmj
75b52fc9a4 Update dev-requirements.txt 2022-10-11 23:23:15 +08:00
grossmj
1952da5876 Update requirements.txt 2022-10-11 23:01:24 +08:00
Jeremy Grossmann
1f620026d4 Merge pull request #3394 from KaisenCAS/master
CVE-2007-4559 patch
2022-10-10 23:31:52 +08:00
grossmj
1d293618e5 Upgrade dependencies 2022-10-10 14:29:04 +08:00
Kevin Chevreuil - Kaisen
2622549ce6 Add a fix for the CVE-2007-4559 2022-10-09 22:55:15 +02:00
grossmj
96e2a42012 Revert "Revert "Dot not allow "no border" style for line items""
This reverts commit 2af2a67fae.
2022-09-08 00:15:43 +02:00
grossmj
2af2a67fae Revert "Dot not allow "no border" style for line items"
This reverts commit 80908feeba.
2022-09-08 00:12:46 +02:00
grossmj
26a0da0564 Development on 3.0.0dev5 2022-09-07 01:16:14 +02:00
grossmj
7b52cd4f81 Release v3.0.0a2 2022-09-07 01:05:41 +02:00
grossmj
f0d12c91a2 Merge branch '2.2' into 3.0
# Conflicts:
#	CHANGELOG
#	dev-requirements.txt
#	gns3/crash_report.py
#	gns3/version.py
2022-08-30 11:43:19 +02:00
grossmj
900bd1c0b4 Development on 2.2.35dev1 2022-08-29 11:14:44 +02:00
grossmj
0b3dbb2843 Release v2.2.34 2022-08-28 23:28:12 +02:00
grossmj
7d0b6bf0d2 Add missing 'sys' module. Ref #3373 2022-08-28 16:40:45 +02:00
grossmj
b45cbeaced Upgrade dev dependencies 2022-08-28 16:12:45 +02:00
grossmj
ef4f6b2b27 Upgrade Sentry dependency 2022-08-28 00:02:54 +02:00
grossmj
e9806345ca Downgrade to pytest v7.0.1 (last version to support 2022-08-27 19:35:36 +02:00
grossmj
ee23e32c75 Upgrade dev dependencies 2022-08-27 19:29:42 +02:00
grossmj
80908feeba Dot not allow "no border" style for line items 2022-08-26 21:54:55 +02:00
grossmj
9a8f2e65de Use "none" for solid line style in drawing items 2022-08-25 22:27:09 +02:00
grossmj
4bb74be5a8 Upgrade dependencies 2022-08-24 12:02:56 +02:00
grossmj
fbeacdcb2a Implement new option (Delete All) to contextual menu in "Console" dock. Fixes #3325 2022-08-16 17:48:58 +02:00
grossmj
da6581d1ac Fix editing Docker container config generates exception and empty config. Fixes #3371 2022-08-10 11:34:21 +02:00
grossmj
1fcb9a4cd4 Merge branch '2.2' into 3.0 2022-08-07 23:56:33 +02:00
grossmj
b3937c7b94 Fix 2560x1440 resolution for Docker container 2022-08-07 23:56:11 +02:00
grossmj
036e9ef8a4 Fix cannot detect images by default when trying to upload them in the Image Manager. Fixes #3367 2022-08-06 13:08:30 +02:00
grossmj
4bb99e7917 Fix unable to set VNC console resolution. Fixes #3365 2022-08-06 12:48:39 +02:00
grossmj
f10c86160f Development on v3.0.0dev4 2022-08-04 12:29:49 +02:00
grossmj
f3b3d7565d Release v3.0.0a1 2022-08-04 11:38:17 +02:00
Jeremy Grossmann
1d0a173689 Merge pull request #3358 from GNS3/use-themed-symbols
Let the controller allocate symbols
2022-07-25 20:45:40 +02:00
grossmj
b2363434a2 Set default symbol theme to "Affinity-square-blue" 2022-07-25 20:38:26 +02:00
grossmj
ca3e6f0472 Fix creating a custom Ethernet switch template 2022-07-25 17:24:28 +02:00
grossmj
f1b19f4633 Update decorative symbols (for Wizards etc.) 2022-07-25 17:13:23 +02:00
grossmj
ed57ac3de5 Use generic symbol names 2022-07-25 15:12:29 +02:00
grossmj
6b35992e5a Set raw image param when uploading an image from the appliance wizard 2022-07-22 12:40:32 +02:00
grossmj
5f97d7891f Fix incorrect param in getCompute() 2022-07-22 12:06:27 +02:00
Jeremy Grossmann
6a46c26a37 Merge pull request #3355 from GNS3/enhancement/2076
Remove valid hostname checks for Dynamips, IOU, Qemu and Docker nodes
2022-07-17 11:56:29 +02:00
grossmj
d43411dafd Checks for valid hostname on server side for Dynamips, IOU, Qemu and Docker nodes 2022-07-17 11:51:29 +02:00
grossmj
0427383457 Upgrade dependencies 2022-07-15 11:32:18 +02:00
grossmj
991387f483 Fix incorrect call to QProgress.setValue() with float 2022-07-12 00:50:50 +02:00
Jeremy Grossmann
8ff966dd54 Merge pull request #3350 from GNS3/import-project
Project import
2022-07-05 23:08:47 +02:00
grossmj
271850cfec Remove "portable" from project import/export references 2022-07-05 23:07:10 +02:00
grossmj
f09c67dd3d Reactivate project importation 2022-07-05 23:01:44 +02:00
grossmj
aea8e01d13 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/http_client.py
#	gns3/modules/docker/ui/docker_vm_configuration_page_ui.py
#	gns3/version.py
2022-06-21 16:33:42 +02:00
grossmj
f2711732db Back to development on v2.2.34dev2 2022-06-21 11:52:58 +02:00
grossmj
148ac4b072 Revert "Development on v2.2.34dev2"
This reverts commit 65eeb79b26.
2022-06-21 11:51:01 +02:00
grossmj
65eeb79b26 Development on v2.2.34dev2 2022-06-21 11:38:09 +02:00
grossmj
537304ce08 Release v2.2.33.1 2022-06-21 10:48:02 +02:00
grossmj
f22df5f016 Development on v2.2.34dev1 2022-06-20 21:47:42 +02:00
grossmj
8dfc8b7714 Release v2.2.33 2022-06-20 20:53:21 +02:00
grossmj
8c6fa9433f Upgrade sentry-sdk and psutil 2022-06-20 20:05:34 +02:00
Jeremy Grossmann
63837578c5 Merge pull request #3340 from GNS3/node-name-checks
Check node names
2022-06-20 19:02:37 +02:00
grossmj
b719703dbe Check that node names for Qemu and Docker are valid 2022-06-18 16:59:14 +02:00
grossmj
084d14c17e Backport reset all console connections. Fixes #2072 2022-06-15 15:58:15 +02:00
grossmj
8c0fca1dd7 Add more video resolutions to Docker containers using VNC. Fixes #3329 2022-06-09 00:26:39 +08:00
grossmj
863d05c923 Add python_requires=">=3.4" in setup.py. Fixes #3326 2022-06-07 18:27:01 +08:00
grossmj
3ebaac8a2c Only allow post release corrective versions of GUI and server to interact 2022-06-07 18:22:06 +08:00
grossmj
16878c9dfa Allow minor versions of GUI and server to interact 2022-06-07 18:06:53 +08:00
grossmj
45da18bb7c Update VirtViewer path. Fixes #3334 2022-06-07 17:35:55 +08:00
Jeremy Grossmann
5615141ed7 Merge pull request #3318 from GNS3/remove-qemu-binaries-requirement
Remove Qemu binary requirement
2022-06-06 14:50:52 +08:00
Jeremy Grossmann
c06491b112 Merge pull request #3336 from GNS3/project-export-zstd
zstandard compression support for project export
2022-06-03 11:32:18 +07:00
grossmj
b01c03855e Support compression levels 2022-06-01 20:26:12 +07:00
grossmj
01e101beac Add zstandard compression 2022-06-01 15:35:01 +07:00
grossmj
18eba37b85 Upgrade dependencies 2022-05-26 19:21:37 +07:00
grossmj
3b7fb3329f Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/ui/main_window.ui
#	gns3/ui/main_window_ui.py
#	gns3/version.py
#	requirements.txt
2022-04-27 22:28:16 +07:00
grossmj
7a6d06ea0c Development on 2.2.33dev1 2022-04-27 19:51:24 +07:00
grossmj
d371042647 Upgrade distro package to v1.7.0 2022-04-27 19:48:50 +07:00
grossmj
0321c11c34 Release v2.2.32 2022-04-27 18:47:20 +07:00
grossmj
522df41a57 Use public DSNs for Sentry 2022-04-20 18:41:18 +07:00
grossmj
afccdf5b9e Fix exception when doubleclick on NAT node. Fixes #3312 2022-04-20 17:55:16 +07:00
grossmj
b2cd24b511 Upgrade some packages 2022-04-20 17:38:54 +07:00
grossmj
6d131a05f1 Fix "Apply" button in the "Preferences" dialog stays gray when templates/nodes are opened by double-click. Fixes #3307 2022-04-20 16:49:22 +07:00
grossmj
35e6156c6c Add 'reset docks' in the view menu. Ref #3317 2022-04-20 15:53:32 +07:00
grossmj
5b901fa115 Remove Qemu binary requirement 2022-04-19 18:21:39 +07:00
Jeremy Grossmann
25bd1aa974 Merge pull request #3315 from GNS3/qemu-disk-images
New implementation to create/resize Qemu disk images
2022-04-14 17:23:43 +07:00
grossmj
b0c374a043 Use controller API to list images 2022-04-13 18:13:18 +07:00
grossmj
548663c964 Use new API endpoints to create/resize Qemu disk images. 2022-04-07 16:23:14 +08:00
grossmj
567cd6485f Fix QFileDialog calls 2022-03-30 18:40:50 +08:00
Jeremy Grossmann
d69f00a370 Merge pull request #3306 from GNS3/image-management
Image management dialog
2022-03-20 19:56:47 +10:00
grossmj
1c6eb5eb4d Image management dialog 2022-03-20 19:28:11 +10:00
grossmj
d3c3ae5143 Use README.md in setup.py 2022-03-16 11:22:28 +10:00
grossmj
f2b2e6f618 Drop Python 3.6 support and require Python >= 3.7 2022-03-14 15:13:27 +10:30
grossmj
a617d5aedf Convert README to markdown 2022-03-13 15:44:26 +10:30
grossmj
9e33cd24bb Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
#	requirements.txt
2022-03-13 14:50:44 +10:30
grossmj
6f767d7455 Upgrade dependencies 2022-03-12 16:23:17 +10:30
grossmj
96d8de4da8 Development on 2.2.32dev1 2022-02-26 20:39:42 +10:30
grossmj
6b5a6f3dfe Release v2.2.31 2022-02-26 18:22:17 +10:30
grossmj
8f82eac321 Development on 2.2.31dev1 2022-02-25 15:59:19 +10:30
grossmj
e03ed64f59 Install setuptools v59.6.0 when using Python 3.6 2022-02-25 15:50:35 +10:30
grossmj
3d702aabd0 Release v2.2.30 2022-02-25 14:51:39 +10:30
grossmj
f5e63c2321 Set setuptools to v60.6.0 2022-02-06 21:02:56 +10:30
grossmj
1047eb916a Upgrade dependencies 2022-02-06 17:33:10 +10:30
grossmj
5dc7d0fbda Upgrade to pywin32 v303. Ref #3290 2022-02-06 17:31:32 +10:30
Jeremy Grossmann
f3ba40de43 Merge pull request #3270 from GNS3/server-settings-refactoring
Consolidation of "Server" settings and simplified wizard
2022-01-16 21:13:26 +10:00
grossmj
7e60e4021b Merge branch '3.0' into server-settings-refactoring
# Conflicts:
#	gns3/dialogs/setup_wizard.py
#	tests/test_link.py
2022-01-16 21:36:38 +10:30
grossmj
2609be98b6 Fix int() call. Ref #3283 2022-01-15 18:57:15 +10:30
grossmj
6286e596c0 Fix QPoint() as unexpected type 'float'. Fixes #3283 2022-01-15 18:55:38 +10:30
grossmj
3c546086ed Fix painter.drawRect() has unexpected type 'float'. Fixes #3282 2022-01-15 18:32:35 +10:30
grossmj
557c47d995 Merge branch 'master' into 3.0
# Conflicts:
#	gns3/version.py
2022-01-11 23:14:01 +10:30
grossmj
f4b2c1c5b9 Fix SpinBox.setValue() requires integer. Fixes #3281 2022-01-11 23:12:54 +10:30
grossmj
e578ecdd8a Development on 2.2.30dev1 2022-01-08 22:52:59 +10:30
grossmj
da8adbaa18 Release v2.2.29 2022-01-08 22:14:59 +10:30
grossmj
6d1333f5fe Clear cache when opening symbol selection dialog. Fixes #3256 2021-12-27 12:43:32 +10:30
grossmj
ce8f9206d9 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/http_client.py
2021-12-25 11:21:10 +10:30
grossmj
92c858dd07 Fix @ in username issue with HTTP authentication. Fixes #3275 2021-12-25 11:19:07 +10:30
grossmj
0c7a12f68c Merge branch 'master' into 2.2 2021-12-25 10:58:46 +10:30
Jeremy Grossmann
a4d08cce8c Merge pull request #3277 from etiennewan/etiennewan-patch-2
Fixed QPoint called with floats
2021-12-25 10:27:00 +10:00
grossmj
e0dd7a66e1 Use '//' operator instead of int() 2021-12-24 13:39:19 +10:30
grossmj
23be668c97 Fix create drawing item calls since mapToScene() returns a QPointF
https://doc.qt.io/qt-5/qgraphicsview.html#mapToScene-4
2021-12-24 13:38:26 +10:30
grossmj
1ac14e0f6d Improvements when connecting and updating computes 2021-12-24 13:08:10 +10:30
Etienne Wan
68d0278140 Fixed QPoint called with floats 2021-12-23 18:37:26 +01:00
grossmj
e0651e349c Use current directory when searching for images. Fixes #3198 2021-12-19 18:54:07 +10:30
Jeremy Grossmann
d8e4c1de4d Merge pull request #3273 from tsndqst/fix_create_link_test
Fix create_link test
2021-12-16 12:26:38 +10:00
Your Name
a5aa9bfb7a Remove problematic lines 2021-12-15 20:13:57 -06:00
grossmj
15889a0ac5 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
2021-12-16 12:35:51 +10:30
grossmj
3e0273848f Development on 2.2.29dev1 2021-12-15 21:38:34 +10:30
grossmj
ec374f173c Release v2.2.28 2021-12-15 13:54:24 +10:30
grossmj
b8abdc79dc Merge branch 'master' into 2.2 2021-12-15 13:52:41 +10:30
Jeremy Grossmann
43744eab7e Merge pull request #3272 from etiennewan/patch-1
Fixed drawLine called with float arguments
2021-12-15 09:28:35 +10:00
Etienne Wan
e16f700e49 Fixed drawLine called with float arguments 2021-12-13 23:27:28 +01:00
grossmj
f38ab34ea0 Fix tests 2021-12-12 17:26:52 +10:30
grossmj
087172d024 Refactor server settings and wizard 2021-12-12 16:35:09 +10:30
grossmj
a46b08bea1 Disable local server and GNS3 VM preferences 2021-12-09 18:52:01 +10:30
grossmj
a6c3e2a4bb Fix project readme edit/refresh 2021-12-09 18:50:36 +10:30
Jeremy Grossmann
f89ff86808 Merge pull request #3266 from GNS3/http-client-refactoring
HTTP client refactoring
2021-12-09 16:31:04 +10:30
grossmj
50cdb2432d Fix tests 2021-12-08 20:03:23 +10:30
grossmj
04ea58395a Image uploading to controller and project export 2021-12-07 23:37:59 +10:30
grossmj
6331f54b88 HTTP client refactoring completed 2021-12-03 18:14:37 +10:30
grossmj
a91683f6ff Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
2021-12-02 14:28:57 +10:30
grossmj
62b7d29e4c Start HTTP client refactoring 2021-12-02 14:22:46 +10:30
grossmj
926aec9089 Upgrade dependencies 2021-11-24 17:48:58 +10:30
grossmj
586b640967 Handle empty compute_id in preferences. Ref #3265 2021-11-24 17:41:40 +10:30
Jeremy Grossmann
925d57b2f8 Merge pull request #3263 from FocusedOne/master
Fixed dead VIX API link
2021-11-23 09:15:54 +10:30
FocusedOne
eceaea1317 Fixed dead VIX API link
Replaced old dead vmware link with current 1.17 version download.
2021-11-22 16:40:01 -06:00
grossmj
52322eb982 Remove direct upload to compute 2021-11-16 16:44:28 +10:30
grossmj
4326785dfc Development on 2.2.28dev1 2021-11-13 16:31:21 +10:30
grossmj
3920c28bde Release v2.2.27 2021-11-12 15:33:53 +10:30
grossmj
b34f51e4b0 Merge branch 'master' into 2.2 2021-11-12 14:50:55 +10:30
grossmj
ef45b2e0f1 Fix symbols in "Symbol selection" dialog are not placed in alphabetical order. Fixes #3245 2021-11-08 22:20:22 +10:30
grossmj
545a9f53a8 Fix links duplicates in topology summary. Fixes #3251 2021-11-08 21:55:29 +10:30
grossmj
340ec2d543 Send JWT token in query string when connecting to websocket. Ref https://github.com/GNS3/gns3-server/pull/1992 2021-11-01 16:52:43 +10:30
grossmj
2d3c7ac0c2 Remove traceng code 2021-10-22 16:11:12 +10:30
grossmj
3cd15e5f1a Option to delete orphaned image files from disk when template is removed. Fixes #3249 2021-10-21 15:59:29 +10:30
grossmj
1a2d3d65c1 Remove Qemu legacy networking code 2021-10-20 15:59:05 +10:30
grossmj
c93a543ccb Update appliance files 2021-10-17 15:09:49 +10:30
grossmj
579fb6ceb8 Merge branch 'master' into 3.0
# Conflicts:
#	gns3/version.py
2021-10-09 12:13:24 +10:30
grossmj
83d9367860 Development on 2.2.27dev1 2021-10-08 21:49:11 +10:30
grossmj
2131f07e5f Merge branch '2.2' 2021-10-08 21:46:38 +10:30
grossmj
cf3e716e63 Release v2.2.26 2021-10-08 21:02:04 +10:30
grossmj
c79f14bcab Open "template configuration" dialog with double click on template name in "Preferences". Fixes #3239 2021-10-08 16:35:25 +10:30
grossmj
acd044a88a Only show "virtio" network adapter when legacy node is enabled. Fixes https://github.com/GNS3/gns3-gui/issues/1969 2021-10-08 15:46:56 +10:30
grossmj
391ac73f1a Merge branch '2.2' into 3.0 2021-10-07 21:01:46 +10:30
grossmj
eedec3f999 Upgrade dependencies and test using Python 3.10 2021-10-07 14:59:54 +10:30
grossmj
c103e2deba Upgrade dependencies 2021-09-23 10:39:27 +09:30
Jeremy Grossmann
f26c638350 Merge pull request #3237 from SDN-Projects/optimization/pip-no-cache-dir
chore : use --no-cache-dir flag to pip in dockerfiles to save space
2021-09-23 09:59:58 +09:30
Pratik Raj
4ea24e622b chore : use --no-cache-dir flag to pip in dockerfiles to save space
using --no-cache-dir flag in pip install ,make sure downloaded packages
by pip don't cached on system . This is a best practice which make sure
to fetch from repo instead of using local cached one . Further , in case
of Docker Containers , by restricting caching , we can reduce image size.
In term of stats , it depends upon the number of python packages
multiplied by their respective size . e.g for heavy packages with a lot
of dependencies it reduce a lot by don't caching pip packages.

Further , more detail information can be found at

https://medium.com/sciforce/strategies-of-docker-images-optimization-2ca9cc5719b6

Signed-off-by: Pratik Raj <rajpratik71@gmail.com>
2021-09-22 15:13:38 +05:30
grossmj
ab854752d9 Double-click on a template opens "template configuration" dialog. Fixes #3236 2021-09-20 20:28:56 +09:30
grossmj
5cee045a65 Fix "Custom symbols" can't be unfolded after using "Filter" field. Fixes #3231 2021-09-20 18:39:32 +09:30
grossmj
48e7ef07cf Isolate and unisolate support. Fixes https://github.com/GNS3/gns3-gui/issues/3190 2021-09-15 18:48:02 +09:30
grossmj
c6f8198974 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
2021-09-15 16:58:57 +09:30
grossmj
37cd82fb44 Development on v2.2.26dev1 2021-09-14 21:13:04 +09:30
grossmj
334eb5175c Release v2.2.25 2021-09-14 19:20:11 +09:30
grossmj
c4561e81eb Support authentication using JWT tokens 2021-09-11 19:53:40 +09:30
grossmj
25841ea7db Fix menu disabled for modal dialogs on macOS. Fixes #3007 2021-09-09 21:21:22 +09:30
grossmj
b3603ea364 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/node.py
#	gns3/version.py
#	win-requirements.txt
2021-09-09 16:27:25 +09:30
grossmj
3d3b4f92b2 Change method to display the recent files menu. Fixes #3007 2021-09-09 09:23:45 +09:30
grossmj
82740da89d Fix bug when using empty port names for custom adapters. Fixes #3228 2021-09-08 16:16:27 +09:30
grossmj
ad19b3dda0 Upgrade PyQt5 to version 5.15.4 for macOS 2021-09-08 15:36:04 +09:30
grossmj
bb8fd18f98 Fix mouse zoom-in/out step value is two times bigger than keyboard one. Fixes #3226 2021-09-08 15:26:56 +09:30
grossmj
336eaf443a Upgrade to Qt 5.15.4 on Windows. Ref #3210 2021-09-08 14:25:25 +09:30
grossmj
0b94be6805 Fix issue with custom adapters at the node level. Fixes #3223 2021-09-05 21:15:30 +09:30
grossmj
671ced78ff Merge branch 'master' into 2.2 2021-09-02 14:45:00 +09:30
Jeremy Grossmann
c8766ce529 Merge pull request #3157 from hrnciar/setuptools
Explicitly require setuptools, utils/get_resource.py imports pkg_resources
2021-08-29 22:06:22 -07:00
Jeremy Grossmann
bec9512c78 Merge branch 'master' into setuptools 2021-08-29 22:02:55 -07:00
grossmj
dd44582347 Merge branch 'master' into 3.0
# Conflicts:
#	dev-requirements.txt
#	gns3/version.py
#	win-requirements.txt
2021-08-29 19:15:35 +09:30
grossmj
b2ad5f4158 Development on 2.2.25dev1 2021-08-25 21:23:19 +09:30
grossmj
966873bc6c Release v2.2.24 2021-08-25 20:31:26 +09:30
grossmj
5b9111b55d Merge branch 'master' into 2.2 2021-08-25 20:08:45 +09:30
grossmj
56688f2236 Update dependencies 2021-08-24 21:12:27 +09:30
grossmj
2e656a9d53 Fix incorrect Qemu binary selected when importing template. Fixes https://github.com/GNS3/gns3-gui/issues/3216 2021-08-24 17:26:07 +09:30
grossmj
2790f707c3 Early support for Python3.10 2021-08-15 15:10:02 +09:30
grossmj
270301d9b5 Bump version to 3.0.0dev3 2021-08-12 16:05:20 +09:30
grossmj
4614543edf Upgrade dependencies 2021-08-10 23:08:14 +09:30
grossmj
80b7ece5a8 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
#	mac-requirements.txt
2021-08-10 15:28:01 +09:30
Jeremy Grossmann
ee9002df61 Merge pull request #3217 from GNS3/dependabot/pip/pywin32-301
Bump pywin32 from 300 to 301
2021-08-09 17:59:04 -07:00
dependabot[bot]
52626e9fe9 Bump pywin32 from 300 to 301
Bumps [pywin32](https://github.com/mhammond/pywin32) from 300 to 301.
- [Release notes](https://github.com/mhammond/pywin32/releases)
- [Changelog](https://github.com/mhammond/pywin32/blob/master/CHANGES.txt)
- [Commits](https://github.com/mhammond/pywin32/commits)

---
updated-dependencies:
- dependency-name: pywin32
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-08-09 20:48:41 +00:00
grossmj
6619c6af97 Add PyQt5==5.12.3 for macOS build 2021-08-07 20:09:41 +09:30
grossmj
60e04c7248 Development on 2.2.24dev1 2021-08-05 21:16:10 +09:30
grossmj
724858f977 Release v2.2.23 2021-08-05 15:58:54 +09:30
Jeremy Grossmann
5a2e05a4fd Merge pull request #3212 from GNS3/handle_no-kvm_deprecated
Handle -no-kvm param deprecated in Qemu >= v5.2
2021-07-27 17:37:45 +09:30
grossmj
010888e3ca Handle -no-kvm param deprecated in Qemu >= v5.2 2021-07-27 16:34:51 +09:30
grossmj
3226921536 Support for invisible links. Fixes #2461 2021-07-27 15:30:58 +09:30
grossmj
022e918301 Add kitty console application command line. Fixes #3203 2021-07-25 16:12:35 +09:30
grossmj
846b19a9e7 Add Windows Terminal profile as an option for Console Applications. Fixes #3193 2021-06-14 13:10:01 +09:30
grossmj
54511b2c45 Upgrade dependencies. 2021-06-12 15:30:38 +09:30
grossmj
ed36917cf3 Fix tests 2021-06-12 15:09:18 +09:30
grossmj
7545c600bc Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/items/link_item.py
#	gns3/main_window.py
#	gns3/ui/resources_rc.py
#	gns3/version.py
#	win-requirements.txt
2021-06-12 14:25:47 +09:30
grossmj
45f5c6e010 Development on 2.2.23dev1 2021-06-10 16:20:10 +09:30
grossmj
963bbb7b89 Release v2.2.22 2021-06-10 15:41:58 +09:30
grossmj
016ad7a775 Fix exception shown when GNS3 is started with empty config. Fixes #3188 2021-06-10 12:28:25 +09:30
grossmj
e8c82566c6 Add ZOC8 console terminal for macOS command line 2021-06-07 19:41:09 +09:30
grossmj
1ed6fceade Fix tests. Ref https://github.com/GNS3/gns3-gui/issues/2461 2021-06-07 14:26:20 +09:30
grossmj
d945fd8b7b Minor changes to style editor dialog. 2021-06-07 14:10:32 +09:30
grossmj
fd6c7eccd0 Link style support. Fixes https://github.com/GNS3/gns3-gui/issues/2461 2021-06-07 14:09:58 +09:30
grossmj
7a1afe2aec Upgrade dependencies 2021-06-07 13:46:06 +09:30
grossmj
6debe56d8e Fix charcoal theme. Ref #3137 2021-06-06 21:45:16 +09:30
grossmj
a4c7d41c26 Fix issue when showing menu to select port. Fixes #3169 2021-05-20 22:15:21 -07:00
grossmj
ea9243dcd9 Merge remote-tracking branch 'origin/2.2' into 2.2 2021-05-20 15:00:49 +09:30
grossmj
e9d8337bd6 Revert "Downgrade to PyQt5 5.12.1. Fixes https://github.com/GNS3/gns3-gui/issues/3169"
This reverts commit ece4d51213.
2021-05-20 14:59:44 +09:30
Jeremy Grossmann
3c92e463f8 Update setup.py
Fixes https://github.com/GNS3/gns3-server/issues/1897
2021-05-16 17:45:11 +09:30
grossmj
4dd7db5a86 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
#	win-requirements.txt
2021-05-15 20:12:52 +09:30
grossmj
3d07db5c5f Development on 2.2.22dev1 2021-05-10 23:44:40 +09:30
grossmj
20cc309ac8 Release v2.2.21 2021-05-10 22:42:47 +09:30
grossmj
262a2839c5 Fix issue with empty project variable name. Fixes #3162 2021-05-10 17:55:06 +09:30
grossmj
ece4d51213 Downgrade to PyQt5 5.12.1. Fixes https://github.com/GNS3/gns3-gui/issues/3169 2021-05-10 17:03:22 +09:30
grossmj
6d2ffc4614 Revert "Rename __json__() to asdict()"
This reverts commit bc14f15a
2021-04-17 23:38:08 +09:30
grossmj
bc14f15a61 Rename __json__() to asdict() 2021-04-17 23:34:28 +09:30
grossmj
2c7de627f7 Merge branch 'master' into 3.0
# Conflicts:
#	gns3/version.py
#	requirements.txt
#	win-requirements.txt
2021-04-10 12:31:08 +09:30
grossmj
0ef39ba129 Development on 2.2.21dev1 2021-04-09 13:50:21 +09:30
grossmj
f90267b4f0 Release v2.2.20 2021-04-09 12:14:38 +09:30
grossmj
8f16706a22 Merge branch 'master' into 2.2 2021-04-09 12:05:15 +09:30
grossmj
2d3ee3abf9 Fix project does not load anymore. Fixes #3140 2021-04-07 16:47:09 +09:30
grossmj
b8b209fa55 Fix errors while connecting to server 2021-04-07 15:51:52 +09:30
grossmj
18129e3d29 Do not connect to server while waiting for user to accept/reject SSL certificate. Fixes #3144 2021-04-07 12:09:38 +09:30
grossmj
7a2b9c024f Fix invalid server version check request. Fixes #3144 2021-04-07 12:03:37 +09:30
grossmj
4923a6dc17 Revert to PyQt5 v5.12.3 because of SSL not working
Probably the SSL DLLs weren't properly found and included by cx_Freeze
2021-04-06 23:01:07 +09:30
grossmj
73dfc047aa Set PyQt5 version to 5.15.2 on Windows 2021-04-06 22:12:34 +09:30
grossmj
fe0a70c4be Upgrade dependencies 2021-04-06 13:57:00 +09:30
Tomas Hrnciar
67014965be Explicitly require setuptools, utils/get_resource.py imports pkg_resources 2021-03-31 11:53:28 +02:00
Jeremy Grossmann
f14cb43404 Merge pull request #3153 from VidVidex/master
Add terminator as a predefined custom console option
2021-03-26 14:53:00 +10:30
Vid
f8517ee5ac Add terminator as a predefined custom console option 2021-03-24 20:28:19 +01:00
grossmj
7dc607b4c5 Development on 2.2.20dev1 2021-03-05 16:48:09 +10:30
grossmj
882fa76550 Release v2.2.19 2021-03-05 14:51:03 +10:30
grossmj
76d9fcf60e Fix merge 2021-02-16 20:58:00 +10:30
grossmj
c3049ea843 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/modules/qemu/pages/qemu_vm_configuration_page.py
#	gns3/modules/qemu/qemu_vm.py
#	gns3/modules/qemu/ui/qemu_vm_configuration_page.ui
#	gns3/modules/qemu/ui/qemu_vm_configuration_page_ui.py
#	gns3/version.py
2021-02-16 20:55:41 +10:30
grossmj
1490a1ad8f Development on 2.2.19dev1 2021-02-16 20:44:58 +10:30
grossmj
aab0c99cc6 Release v2.2.18 2021-02-16 19:09:46 +10:30
grossmj
a6a987d74c Fix bug with SSL connection on projet websocket stream. 2021-02-16 17:42:18 +10:30
grossmj
9c58b18c20 Merge remote-tracking branch 'origin/2.2' into 2.2 2021-02-16 16:42:45 +10:30
grossmj
8bc499c68f Bump version to 2.2.18dev2 2021-02-16 16:35:26 +10:30
Jeremy Grossmann
bd5eb288b7 Merge pull request #3130 from GNS3/ssl-support
SSL support.
2021-02-16 16:16:32 +10:30
grossmj
465a289568 SSL support. 2021-02-16 16:08:27 +10:30
grossmj
d240ba3056 Merge remote-tracking branch 'origin/2.2' into 2.2 2021-01-26 23:11:11 +10:30
grossmj
3cedfd3649 Remove the useless file "zoom-in (copy).svg". Fixes #3114 2021-01-26 23:10:34 +10:30
Jeremy Grossmann
276d7abdd9 Merge pull request #3104 from b-ehlers/QemuConfig
Add Qemu config disk
2020-12-14 14:23:09 +10:30
grossmj
d6432c2e88 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/version.py
2020-12-07 17:56:09 +10:30
grossmj
927e38bd6d Development on 2.2.18dev1 2020-12-04 18:10:11 +10:30
grossmj
376cc29995 Release v2.2.17 2020-12-04 16:26:56 +10:30
grossmj
1f8ebeb084 Merge branch 'master' into 2.2 2020-12-04 16:21:42 +10:30
grossmj
0212755c78 Remove "-nographic" option by default for Qemu VM. Fixes #3094 2020-12-02 18:44:18 +10:30
Jeremy Grossmann
2f7d75eae9 Fix app cannot start on macOS Big Sur. Ref #3037 2020-11-30 20:02:52 +10:30
Jeremy Grossmann
fc1c060922 Merge pull request #3097 from SpikefishSolutions/master
Add yes/no prompts to gui for global project level buttons start/stop/reload/suspend to prevent bad day.
2020-11-21 18:32:45 +10:30
John
0ea72ce782 one more spacing update 2020-11-20 21:33:44 -05:00
John
3de2d2eda2 spacing updates 2020-11-20 21:32:26 -05:00
John
c08262f8af Correct stop/start/reload/suspend button names 2020-11-20 21:26:08 -05:00
John
9ae70bf2fe Add yes/no prompts to all major buttons 2020-11-20 21:11:15 -05:00
John
fa6d250602 oops.. need to build after commit. 2020-11-20 20:27:43 -05:00
John
0668840a2b i don't get it. 2020-11-20 20:26:19 -05:00
John
8b25d1b06c can't fix indent? 2020-11-20 20:25:06 -05:00
John
58c3ba0755 update indent 2020-11-20 20:23:46 -05:00
John
5a91c9aaf8 Create a message box for stopping all devives instead of blindly making someone's day terrible. 2020-11-20 18:28:30 -05:00
grossmj
89b9e6c332 Providing the path to create a project is now deprecated. 2020-11-13 15:17:55 +10:30
grossmj
54b5d8f347 Upgrade packages to latest versions 2020-11-08 21:35:55 +10:30
grossmj
237ef785ad Fix tests 2020-11-05 18:26:15 +10:30
grossmj
0ddd91af43 Merge branch '2.2' into 3.0
# Conflicts:
#	gns3/link.py
#	gns3/version.py
2020-11-05 17:05:58 +10:30
grossmj
0fc3f4ef16 Development on 2.2.17dev1 2020-11-05 16:59:58 +10:30
grossmj
f0e5cd2ba2 Release v2.2.16 2020-11-05 15:38:19 +10:30
grossmj
f59ef6378a Fix broken security link (replaced by email). Fixes #3085 2020-11-05 15:00:04 +10:30
grossmj
61ef08d1b7 Fix packets capture stops after some time. Fixes #3067 2020-11-05 14:21:22 +10:30
grossmj
e812c000fd Option to allocate or not the vCPUs and RAM settings for the GNS3 VM. Fixes https://github.com/GNS3/gns3-gui/issues/3069 2020-11-05 11:13:57 +10:30
grossmj
7f5db61722 Client to use version 3 of the API. 2020-11-02 18:15:43 +10:30
grossmj
fcc5c4c114 Merge remote-tracking branch 'origin/3.0' into 3.0 2020-10-19 18:28:30 +10:30
grossmj
68f3dc763d Fix some API calls. 2020-10-19 18:28:17 +10:30
Bernhard Ehlers
d3d9e1e8ae Use HDD disk image as startup QEMU config disk 2020-10-19 03:45:27 +02:00
Jeremy Grossmann
786306304b Merge pull request #3075 from b-ehlers/fix_hdd_layout
Fix HDD configuration layout
2020-10-16 19:21:41 +10:30
Bernhard Ehlers
05f8df345a Fix HDD configuration layout
(cherry picked from commit 4f631669e5)
2020-10-16 10:22:32 +02:00
Bernhard Ehlers
4f631669e5 Fix HDD configuration layout 2020-10-16 10:22:32 +02:00
grossmj
0b8fb93752 Merge branch '2.3' into 3.0
# Conflicts:
#	gns3/version.py
2020-10-12 21:21:51 +10:30
grossmj
422f6004b1 Bump version to 3.0.0dev1 2020-10-12 17:48:32 +10:30
grossmj
717d683b44 Merge branch '2.2' into 3.0 2020-10-12 17:47:26 +10:30
grossmj
4b0cc11cab Development on 2.2.16dev1 2020-10-07 16:30:03 +10:30
grossmj
b5285cd142 Release v2.2.15 2020-10-07 15:29:52 +10:30
grossmj
69482343ba Fix custom symbol not sent to remote controller when installing appliance 2020-10-07 15:09:08 +10:30
grossmj
932f737ed9 Create branch 3.0 2020-10-06 11:59:24 +10:30
grossmj
d4639c2e61 Development on 2.2.15dev1 2020-09-15 06:49:11 +09:30
grossmj
b85ade9dd7 Release v2.2.14 2020-09-15 05:52:48 +09:30
grossmj
e191cb8aa3 Fix tests. Ref #3002 2020-09-14 00:10:11 +09:30
grossmj
e6bc75ce26 Improvements to add a new version of an appliance from wizard. Fixes #3002. 2020-09-14 00:04:58 +09:30
grossmj
bc1df346f2 Development on 2.2.14dev1 2020-09-05 04:26:16 +09:30
grossmj
27c35321f0 Release v2.2.13 2020-09-04 23:13:28 +09:30
grossmj
64a0ee37de Change Qemu disk descriptions. Fixes #3035 2020-08-18 18:07:01 +09:30
Jeremy Grossmann
ec8d214c08 Merge pull request #3040 from b-ehlers/edit_config_text
Edit only text mode config files
2020-08-18 08:44:56 +08:00
Bernhard Ehlers
3e212fc629 Edit only text mode config files
(cherry picked from commit 880ac5e8c3)
2020-08-18 02:27:31 +02:00
Bernhard Ehlers
880ac5e8c3 Edit only text mode config files 2020-08-18 02:27:31 +02:00
Jeremy Grossmann
feb40a6250 Merge pull request #3039 from b-ehlers/hide_empty_config
Hide config import/export when configFiles attribute is empty
2020-08-17 19:36:34 +08:00
Bernhard Ehlers
25e41dc0f1 Hide config import/export when configFiles attribute is empty
(cherry picked from commit fd7b915e96)
2020-08-17 13:09:59 +02:00
Bernhard Ehlers
fd7b915e96 Hide config import/export when configFiles attribute is empty 2020-08-17 13:09:59 +02:00
grossmj
5fbb6cbf61 Qemu disk interfaces must be set to "none" by default. Ref #3035 2020-08-17 12:49:21 +09:30
grossmj
c58c7774c4 Qemu disk interfaces must be set to "none" by default. Ref #3035
(cherry picked from commit 5fbb6cbf61)
2020-08-17 12:49:21 +09:30
Jeremy Grossmann
fda948cc5b Merge pull request #3024 from GNS3/qemu-config-disk
QEMU config disk - enable QEMU config import/export
2020-08-15 16:40:13 +08:00
Jeremy Grossmann
a9b18f1771 Merge branch '2.3' into qemu-config-disk 2020-08-15 16:36:58 +08:00
grossmj
bd2bc8265c Do not allow image to be configured on Qemu VM secondary slave disk if create config disk option is enabled.
(cherry picked from commit 04f9a1cf8c)
2020-08-15 16:05:43 +09:30
grossmj
04f9a1cf8c Do not allow image to be configured on Qemu VM secondary slave disk if create config disk option is enabled. 2020-08-15 16:05:43 +09:30
grossmj
f2209a2780 Add explicit option to automatically create or not the config disk. Off by default.
(cherry picked from commit af79471afd)
2020-08-14 17:57:24 +09:30
grossmj
af79471afd Add explicit option to automatically create or not the config disk. Off by default. 2020-08-14 17:57:24 +09:30
grossmj
6067786783 Bump version to 2.3.0dev2 2020-08-13 01:49:25 +09:30
grossmj
090fc63bb6 Merge branch '2.2' into 2.3
# Conflicts:
#	gns3/version.py
2020-08-13 01:48:49 +09:30
Jeremy Grossmann
029a1df7f7 Merge pull request #3029 from GNS3/aux-console-refactoring
Auxiliary console support
2020-08-12 15:59:04 +08:00
grossmj
7b99ba325b Development on 2.2.13dev1 2020-08-07 21:12:46 +09:30
grossmj
74763287fb Release v2.2.12 2020-08-07 19:27:32 +09:30
grossmj
737ff42d64 Merge branch 'master' into 2.2 2020-08-07 19:04:08 +09:30
Jeremy Grossmann
b47aa95b3e Downgrade psutil to version 5.6.7 2020-07-29 17:36:46 +09:30
Jeremy Grossmann
5656bd2d48 Downgrade psutil to version 5.6.7 2020-07-29 17:36:14 +09:30
grossmj
ffb364591f Auxiliary console support for Qemu. Ref #2873
Improvements for auxiliary console support for Docker and Dynamips.
2020-07-29 16:23:51 +09:30
Jeremy Grossmann
058c069394 Fix log shows the GUI command line without spaces between its arguments. Fixes #3026 2020-07-27 18:27:23 +09:30
grossmj
6a9440c978 Support to reset all console connections. Ref https://github.com/GNS3/gns3-server/issues/1619 2020-07-26 18:27:18 +09:30
grossmj
758054cfd3 Support to reset links. Fixes https://github.com/GNS3/gns3-server/issues/1620 2020-07-24 21:48:49 +09:30
grossmj
39e6a6e2ab Fix bug when recent files cannot be seen in the new project dialog. 2020-07-24 18:49:32 +09:30
grossmj
7a74685c0a Wait for the controller to be online before allowing actions like creating or opening a project. Fixes #2907 2020-07-22 17:32:01 +09:30
grossmj
926ec48d00 Upgrade to psutil version 5.7.2 2020-07-21 15:49:58 +09:30
grossmj
f48eff2344 Upgrade to psutil version 5.7.2 2020-07-21 15:49:06 +09:30
grossmj
b8a583d3f6 Show progress dialog immediately when connecting to server. Ref #2907 2020-07-20 19:14:54 +09:30
Bernhard Ehlers
d01f15c4df QEMU config disk - enable QEMU config import/export 2020-07-19 17:56:24 +09:30
grossmj
3cbad22a04 Fix tests 2020-07-19 14:27:09 +09:30
grossmj
c61a99e78d Add total RAM, CPUs and disk size to servers summary as well as disk usage in percent. Fixes https://github.com/GNS3/gns3-server/issues/1532 2020-07-19 14:16:07 +09:30
Jeremy Grossmann
e318610983 Merge pull request #3023 from GNS3/docker-resource-constraints
Resource constraints for Docker VMs.
2020-07-18 19:39:08 +08:00
grossmj
ab7cc29fa2 Resource constraints for Docker VMs. 2020-07-18 21:03:55 +09:30
grossmj
2788019e17 Do not show project readme when loading a snapshot. 2020-07-18 17:41:05 +09:30
grossmj
410e5353b2 Use server host is console host is equal to "0:0:0:0:0:0:0:0" 2020-07-17 21:13:27 +09:30
grossmj
bfb90406ed Remove VMware promotion. 2020-07-17 21:12:59 +09:30
grossmj
819bb1c58e Wait for readme to be updated before exporting the project. 2020-07-17 16:36:35 +09:30
grossmj
723f806a52 Support for "usage" for "Cloud" nodes. Fixes https://github.com/GNS3/gns3-gui/issues/2887
Allow "usage" for all builtin nodes (not exposed in Ui).
2020-07-15 19:15:51 +09:30
grossmj
a5093e06d1 Markdown support in project Readme. Fixes #2550 #2289
Allow project README to be edited from "File->Edit project". Fixes #2829
2020-07-14 22:40:05 +09:30
grossmj
f33c01ac58 Bump PyQt version to 5.15.0 LTS. Ref #3020 2020-07-13 14:07:38 +09:30
grossmj
8c382e5b7d Bump version to 2.3.0dev1 2020-07-11 11:41:51 +09:30
grossmj
439cdce287 Development on 2.2.12dev1 2020-07-09 21:37:03 +09:30
grossmj
4e50c2a4b1 Release v2.2.11 2020-07-09 20:37:10 +09:30
grossmj
94c636ae61 Merge branch 'master' into 2.2 2020-07-09 20:23:31 +09:30
grossmj
f53b9a266e Try to fix "Recent project" selection not working. Ref #3007 2020-07-09 15:37:47 +09:30
grossmj
2476448032 Fix debug entries shown twice in console window and double error messages with remote GNS3VM. Fixes #3010 #3011
Note that the debug level is broken (has been for a long time apparently).
2020-07-07 21:06:56 +09:30
grossmj
a34cd742e3 Merge branch '2.2' 2020-07-06 22:20:05 +09:30
grossmj
39698196ac Fix deprecation warning. Ref #3009 2020-07-06 22:08:10 +09:30
grossmj
61432ced4f Fix tests on macOS. Ref #3009 2020-07-06 22:03:29 +09:30
grossmj
2ddd13c445 Add Snyk badges. 2020-06-27 18:27:04 +09:30
grossmj
af6c4c5b3e Merge branch 'master' into 2.2 2020-06-26 21:30:37 +09:30
grossmj
d4012294bf Run tests inside container 2020-06-26 20:50:48 +09:30
grossmj
4b04b0e855 Use xvfb to run tests 2020-06-26 20:41:08 +09:30
grossmj
1bec5019bf Install PyQt5 using pip 2020-06-26 19:42:42 +09:30
grossmj
ec6b876baa Explicitly install sip 2020-06-26 19:38:10 +09:30
grossmj
7cee0d01ab Install PyQt5 for tests and add GitHub Actions badge 2020-06-26 19:34:02 +09:30
Jeremy Grossmann
dd3314d06b Set up GitHub Actions for running tests 2020-06-26 19:27:22 +09:30
grossmj
9c58b26265 Remove tox, Travis CI and pep8.sh script
Update dependencies
2020-06-26 19:21:51 +09:30
Jeremy Grossmann
83c26f47da Merge pull request #3005 from GNS3/whitesource/configure
Configure WhiteSource for GitHub.com
2020-06-26 09:04:39 +08:00
whitesource-for-github-com[bot]
8ed2f55600 Add .whitesource configuration file 2020-06-26 01:01:54 +00:00
Jeremy Grossmann
b435317904 Merge pull request #3003 from GNS3/snyk-fix-8bf3e4840df4587cc42afb85b857d470
[Snyk] Security upgrade psutil from 5.6.6 to 5.6.7
2020-06-25 11:41:01 +08:00
snyk-bot
acb8aa8ca2 fix: requirements.txt to reduce vulnerabilities
The following vulnerabilities are fixed by pinning transitive dependencies:
- https://snyk.io/vuln/SNYK-PYTHON-PSUTIL-483082
2020-06-24 13:10:33 +00:00
grossmj
c55d6b8a6f Fix sentry SDK is configured twice. 2020-06-24 12:40:06 +09:30
grossmj
a4039a254e Development on 2.2.11dev1 2020-06-18 19:06:00 +09:30
grossmj
85ed4b3026 Release v2.2.10 2020-06-18 12:29:33 +09:30
grossmj
5207a99692 New fix for multi-device selection/deselection not working as expected with right click. Fixes #2986 2020-06-09 13:50:31 +09:30
grossmj
d69527995d Revert "Fix Multi-device selection/deselection not working as expected with right click. Fixes #2986"
This reverts commit ddeb95cb0a.
2020-06-09 13:19:20 +09:30
grossmj
4b000ba2f7 Optimize snap-to-grid code for drawing items. Fixes #2997 2020-06-09 11:47:05 +09:30
grossmj
1b302b77a0 Move jsonschema 2.6.0 requirement in build repository.
https://github.com/GNS3/gns3-server/issues/1751
https://github.com/GNS3/gns3-gui/issues/2849

This is to avoid the following error:

```
ERROR: Double requirement given: jsonschema==2.6.0 (from -r gns3-gui\win-requirements.txt (line 4)) (already in jsonschema==3.2.0 (from -r gns3-gui\requirements.txt (line 1)), name='jsonschema')
```
2020-06-07 13:07:16 +09:30
grossmj
a5b5c404ec Only use jsonschema 2.6.0 on Windows and macOS.
https://github.com/GNS3/gns3-server/issues/1751
https://github.com/GNS3/gns3-gui/issues/2849
2020-06-07 12:55:22 +09:30
grossmj
6b97b0c6cd Disable default integrations for sentry sdk. 2020-06-06 15:37:17 +09:30
grossmj
115dd43eee Development on 2.2.10dev1 2020-06-04 21:06:30 +09:30
grossmj
2530bf97a8 Release v2.2.9 2020-06-04 18:39:27 +09:30
grossmj
9892fd0654 Fix issue editing README.txt on Windows. 2020-06-04 18:12:50 +09:30
grossmj
c71ee73da8 Merge branch 'master' into 2.2 2020-06-04 12:22:11 +09:30
Jeremy Grossmann
0643fd516d Merge pull request #2993 from GNS3/replicate-network-connection-state
Support to activate/deactive network connection state replication in Qemu
2020-06-04 10:49:41 +08:00
grossmj
a25680f2ce Fix GUI doesn't detect another GUI on macOS. Fixes #2994 2020-06-03 20:38:55 +09:30
grossmj
58bd5be920 Support to activate/deactive network connection state replication in Qemu. 2020-06-02 18:45:22 +09:30
Jeremy Grossmann
d95633ba2c Merge pull request #2989 from GNS3/reset-mac-addresses
Option to reset all MAC addresses when exporting or duplicating a project.
2020-05-27 10:53:22 +08:00
grossmj
dfea6d1723 Option to reset or not all MAC addresses when exporting or duplicating a project. 2020-05-27 12:14:47 +09:30
grossmj
ddeb95cb0a Fix Multi-device selection/deselection not working as expected with right click. Fixes #2986 2020-05-26 16:11:53 +09:30
grossmj
5f7ff0d70d Generate MainWindow Ui file. 2020-05-26 13:01:04 +09:30
Jeremy Grossmann
a00e039cec Merge pull request #2875 from fatoms/master
Proposed fix for "Edit readme" is missing in GNS3 GUI. #2854
2020-05-26 11:30:19 +08:00
Dominic
a24e9adef1 Merge branch 'Edit_Readme' 2020-05-21 20:03:03 +02:00
Dominic Harford
ee5f8e8edd Resolve conflict with GNS3 repo 2020-05-21 19:08:29 +02:00
grossmj
f5470130f5 Fix issues with crash reporting & bump version to 2.2.9dev2. Ref https://github.com/GNS3/gns3-server/issues/1758 2020-05-21 18:19:19 +09:30
grossmj
1ff405885e Merge branch 'master' into 2.2 2020-05-20 17:25:37 +09:30
Dominic
9fb42ead9f Revert "Updated GUI pyqt files from Tab Order 'fixes' in "Tab Order in Preferences and Project Dialog #2872""
This reverts commit 0d2f91709c.
2020-05-19 18:31:02 +02:00
grossmj
2ea1946c0f Replace Raven by Sentry SDK. Fixes https://github.com/GNS3/gns3-server/issues/1758 2020-05-19 15:48:53 +09:30
grossmj
963e054918 Fix online help menu URL. Fixes #2984 2020-05-08 12:42:06 +09:30
grossmj
0f5f6ab645 Require setuptools>=17.1 in setup.py. Ref https://github.com/GNS3/gns3-server/issues/1751
This is to support environmental markers.
https://github.com/pypa/setuptools/blob/master/CHANGES.rst#171
2020-05-08 12:34:58 +09:30
grossmj
8a905b5c39 Development on 2.2.9dev1 2020-05-07 23:10:20 +09:30
grossmj
e917193f06 Merge branch '2.2' 2020-05-07 23:09:04 +09:30
grossmj
16846ce49c Release v2.2.8 2020-05-07 18:10:57 +09:30
grossmj
624a670ae7 Make sure "port" is defined. 2020-05-07 17:51:32 +09:30
grossmj
406326ccd8 Merge remote-tracking branch 'origin/master' 2020-05-06 11:57:25 +09:30
grossmj
24bc15fb73 Default port set to 80 for server running in the GNS3 VM. Fixes #1737 2020-05-05 12:40:50 +09:30
grossmj
348d8b9438 Make the Web UI the default page. Ref https://github.com/GNS3/gns3-server/issues/1737 2020-04-30 17:27:06 +09:30
grossmj
6787982408 Fix "export portable project forgets contents of README". Fixes #1724 2020-04-30 16:43:00 +09:30
Jeremy Grossmann
c2384917fa Update README. Ref https://github.com/GNS3/gns3-server/issues/1719 2020-04-29 15:01:45 +09:30
grossmj
b80178d0cf Activate unified title and toolbar on MacOS. Fixes #2968 2020-04-29 13:08:51 +09:30
grossmj
e6084ed834 Confirmation dialog for "console connect to all nodes". Fixes #2971 2020-04-28 15:04:39 +09:30
grossmj
ba924cd0d9 Add "Resume all suspended links". Fixes #2858 2020-04-28 14:00:26 +09:30
grossmj
0c3d43346f Revert "Change default path for SecureCRT. Fixes #2896"
This reverts commit 0c4367d77e.
2020-04-28 13:19:38 +09:30
grossmj
fcf6ef3027 Remove @property from ConfigurationDialog(). Fixes #2819 #2965 2020-04-28 11:57:54 +09:30
grossmj
e0f87e573d Use Environmental Markers to force jsonschema version. Fixes https://github.com/GNS3/gns3-gui/issues/2849
Version 3.2.0 with Python >= 3.8
Version 2.6.0 with Python < 3.8
2020-04-27 12:54:17 +09:30
grossmj
3ec068f0cb Use Environmental Markers to force jsonschema version 2.6.0 on Windows/macOS. Ref https://github.com/GNS3/gns3-gui/issues/2849 2020-04-27 12:43:07 +09:30
grossmj
37f1fcf6f7 Remove preferences dialog geometry restoration. Fixes #2807 2020-04-27 11:55:01 +09:30
grossmj
c51dd1605d Merge branch '2.3'
# Conflicts:
#	gns3/version.py
2020-04-13 11:57:04 +09:30
grossmj
4ebf3b4e1c Development on 2.2.8dev1 2020-04-08 01:26:42 +09:30
grossmj
b1ec9d535c Release v2.2.7 2020-04-08 00:03:13 +09:30
grossmj
7fc9087cf0 Fix unable to configure custom adapters for Qemu VMs. Fixes #2961 2020-04-07 15:47:53 +09:30
Bernhard Ehlers
5dc2c77806 QEMU config disk - enable QEMU config import/export
(cherry picked from commit d01f15c4df)
2020-04-06 13:42:00 +02:00
grossmj
4972d460d2 Fix tests. 2020-04-06 21:09:47 +09:30
grossmj
c388836be7 Fix VNC console template doesn't extract %i (Project UUID). Fixes #2960 2020-04-06 18:34:37 +09:30
grossmj
18ae4a6ce9 Fix contextual menu issues. Ref #2955 2020-03-30 21:37:52 -07:00
grossmj
3020e1fc9f Downgrade to PyQt 5.12.3 Ref #2955 #2952 2020-03-29 18:18:53 +10:30
grossmj
fe2f8424db Downgrade to PyQt 5.13.2 Ref #2955 #2952 2020-03-29 14:46:34 +10:30
grossmj
a744f65199 Merge branch 'master' into 2.3
# Conflicts:
#	gns3/version.py
2020-03-28 13:44:08 +10:30
grossmj
d27578f0fc Release v2.2.6 2020-03-26 12:37:59 +10:30
grossmj
b01c11f19b Prevent locked drawings to be deleted. Fixes https://github.com/GNS3/gns3-gui/issues/2948 2020-03-16 16:30:09 +10:30
grossmj
fb269da4d3 Fix issues with empty project variables. Fixes https://github.com/GNS3/gns3-gui/issues/2941 2020-03-14 17:22:44 +10:30
grossmj
ab15f96bb5 Upgrade psutil to version 5.6.6 due to CVE-2019-18874
https://github.com/advisories/GHSA-qfc5-mcwq-26q8
2020-03-14 15:47:12 +10:30
grossmj
5bb8b8e8bd Use existing README.txt if existing when exporting portable project. Fixes https://github.com/GNS3/gns3-server/issues/1724 2020-03-10 17:32:13 +10:30
grossmj
3f9632fae0 Allow creation of a diskless Qemu VMs. Fixes #2939 2020-03-10 17:04:07 +10:30
grossmj
b5f8195abb Re-enable "create new version" in appliance wizard. Fixes #2837 2020-03-03 13:11:01 +08:00
grossmj
73a293bd17 Fix unable to load project from project library. Fixes #2932 2020-03-03 09:34:45 +08:00
grossmj
0a1dfb99e9 Merge remote-tracking branch 'origin/2.2' into 2.2 2020-02-19 14:13:16 +08:00
grossmj
d352919264 Fix some permission denied errors when loading remote project. Ref #2871 Fixes #2901 2020-02-19 14:13:03 +08:00
Jeremy Grossmann
65f2a1e461 Merge pull request #2931 from inthought/2.2
Add 'Royal TS V5' to predefined console list
2020-02-18 13:29:46 +10:30
Travis Abram
71f289721b Add 'Royal TS V5' to predefined console list 2020-02-16 20:46:40 -08:00
grossmj
c28089d400 Disallow invalid grid sized. Fixes #2908 2020-02-10 16:59:17 +08:00
grossmj
64f009bf71 Check if hostname is blank. Fixes #2924 2020-01-25 18:21:02 +08:00
Jeremy Grossmann
edb2fd7fd9 Merge pull request #2925 from GNS3/qemu-changes
GUI changes to support recent versions of Qemu
2020-01-25 16:04:54 +07:00
grossmj
62e7ad8c8a Add nvme disk interface and fix scsi disk interface for Qemu VMs. 2020-01-25 16:22:34 +08:00
grossmj
caeb5d71c3 Add latest Qemu nic models. 2020-01-24 19:05:46 +08:00
grossmj
cfe96b2311 Upgrade Qt version to 5.14.1. Ref #2778 #2903 2020-01-24 17:47:01 +08:00
grossmj
8955b9ee29 Upgrade to PyQt 5.14.1. Ref #2778 2020-01-22 17:53:04 +08:00
grossmj
e727abf27a Change version to 2.3.0dev1 on 2.3 branch 2020-01-16 18:06:51 +08:00
grossmj
f209bf7644 Development on 2.2.6dev1 2020-01-10 00:32:10 +08:00
grossmj
5860dedc32 Release v2.2.5 2020-01-09 23:52:40 +08:00
grossmj
9e2df17a4e Add gns3-gui.xml and update Linux icons paths & permissions. Ref #2919 2020-01-09 23:49:44 +08:00
grossmj
a95761437a Development on 2.2.5dev1 2020-01-09 05:17:01 +08:00
grossmj
626510865f Update paths to icons for Linux 2020-01-09 04:19:21 +08:00
grossmj
2e248aa340 Release v2.2.4 2020-01-09 00:45:09 +08:00
grossmj
e306f73f01 Fix "Console to all nodes" doesn't open cloud objects with console configured. Fixes #2902 2020-01-08 00:35:57 +08:00
grossmj
0c4367d77e Change default path for SecureCRT. Fixes #2896 2019-12-26 06:13:23 +08:00
grossmj
6dda0ff787 Add icons in setup.py Ref #2898 2019-12-26 06:04:40 +08:00
grossmj
d7d4b84309 Add remote viewer as a VNC console for Linux. Fixes #2913 2019-12-26 04:13:02 +08:00
grossmj
7b57983699 Development on 2.2.4dev1 2019-11-12 16:43:21 +08:00
grossmj
bb89fe2275 Release v2.2.3 2019-11-12 15:29:54 +08:00
grossmj
7eb2a923b2 Fix issue when binding on 0.0.0.0. Fixes #2892 2019-11-11 17:49:09 +08:00
grossmj
58052e3cce Allow double click on cloud with configured console to open session. Fixes #2894 2019-11-11 14:31:35 +08:00
grossmj
e431104f6b Officially support Python 3.8. Ref https://github.com/GNS3/gns3-gui/issues/2895 2019-11-11 12:56:11 +08:00
grossmj
a4e9d6b8ce Set psutil to version 5.6.3 in requirements.txt 2019-11-08 10:44:17 +08:00
grossmj
f58f5c7b95 Developement version on 2.2.3dev1 2019-11-04 19:45:18 +08:00
Dominic
c8a8663ff0 Restore editReadme attribute which was removed in Change 'New export project wizard' ( ID c2472bcb22 ) 2019-10-18 17:11:28 +02:00
Dominic
d27e5c1795 Revert "Remove unused edit readme action. Fixes #2816"
This reverts commit 7cd0187f33.
2019-10-18 16:46:48 +02:00
Dominic
0d2f91709c Updated GUI pyqt files from Tab Order 'fixes' in "Tab Order in Preferences and Project Dialog #2872" 2019-10-18 16:45:39 +02:00
259 changed files with 101161 additions and 121917 deletions

19
.github/workflows/testing.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: testing
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build and run Docker image
run: |
docker build -t gns3-gui-test .
docker run gns3-gui-test

View File

@@ -1,2 +0,0 @@
branch:
2.2

View File

@@ -1,21 +0,0 @@
sudo: required
services:
- docker
notifications:
email: false
script:
- docker build -t gns3-gui-test .
- docker run gns3-gui-test
before_deploy:
- sudo pip install twine
- sudo pip install urllib3[secure]
deploy:
provider: pypi
edge:
branch: v1.8.45
user: noplay
password:
secure: FofcqlJjgqf2jaDaXpLHeigVoexbrOz3WwnDuiJpwJxeFUlPY8s2cQs/Bm+dzxzZaOaGiVE0A83v/Xa10yD5tflThHt4sqYJK3iQCinA7wgeAlDimB4xrWUNplfNJZ/Eod5Ssa++E02W+3i29PxpXY//mjCY7qDxaoxul1gnFJY=
on:
tags: true
repo: GNS3/gns3-gui

13
.whitesource Normal file
View File

@@ -0,0 +1,13 @@
{
"scanSettings": {
"configMode": "AUTO",
"configExternalURL": "",
"projectToken" : ""
},
"checkRunSettings": {
"vulnerableCheckRunConclusionLevel": "failure"
},
"issueSettings": {
"minSeverityLevel": "LOW"
}
}

334
CHANGELOG
View File

@@ -1,5 +1,339 @@
# Change Log
## 3.0.0a3 27/12/2022
* Catch timeout error while updating appliance files
* Fix RecursionError with invalid credentials. Fixes #3374
* Allow raw images by default. Fixes https://github.com/GNS3/gns3-server/issues/2097
* Remove deprecated PuTTY option in preferences. Ref https://github.com/GNS3/gns3-gui/discussions/3415
* Fix "variables": [] in project file leads to unlimited increase of empty name/value pairs in GUI. Fixes #3397
* Ignore local revision when comparing versions.
* Make version PEP 440 compliant
* Support for Python 3.11
* Replace deprecated distro.linux_distribution() call
* Add a fix for the CVE-2007-4559
## 2.2.35.1 10/11/2022
* Re-release Web-Ui v2.2.35
## 2.2.35 08/11/2022
* Fix "variables": [] in project file leads to unlimited increase of empty name/value pairs in GUI. Fixes #3397
* Make version PEP 440 compliant
* Support for Python 3.11
* Upgrade PyQt to 5.15.7 and pywin32 to v305
* Allow for more dependency versions at patch level
* Replace deprecated distro.linux_distribution() call
* Add a fix for the CVE-2007-4559
## 3.0.0a2 06/09/2022
* Add missing 'sys' module. Ref #3373
* Upgrade dev dependencies
* Dot not allow "no border" style for line items
* Use "none" for solid line style in drawing items
* Implement new option (Delete All) to contextual menu in "Console" dock. Fixes #3325
* Fix editing Docker container config generates exception and empty config. Fixes #3371
* Fix 2560x1440 resolution for Docker container
* Fix cannot detect images by default when trying to upload them in the Image Manager. Fixes #3367
* Fix unable to set VNC console resolution. Fixes #3365
## 3.0.0a1 04/08/2022
* Set default symbol theme to "Affinity-square-blue"
* Fix creating a custom Ethernet switch template
* Update decorative symbols (for Wizards etc.)
* Use generic symbol names
* Set raw image param when uploading an image from the appliance wizard
* Checks for valid hostname on server side for Dynamips, IOU, Qemu and Docker nodes
* Support compression levels
* Add zstandard compression
* Remove Qemu binary requirement
* Use controller API to list images
* Use new API endpoints to create/resize Qemu disk images.
* Image management dialog
* Drop Python 3.6 support and require Python >= 3.7
* Improvements when connecting and updating computes
* Use current directory when searching for images. Fixes #3198
* Refactor server settings and wizard
* Disable local server and GNS3 VM preferences
* Image uploading to controller and project export
* HTTP client refactoring
* Handle empty compute_id in preferences. Ref #3265
* Remove direct upload to compute
* Send JWT token in query string when connecting to websocket. Ref https://github.com/GNS3/gns3-server/pull/1992
* Remove traceng code
* Option to delete orphaned image files from disk when template is removed. Fixes #3249
* Remove Qemu legacy networking code
* Isolate and unisolate support. Fixes https://github.com/GNS3/gns3-gui/issues/3190
* Support authentication using JWT tokens
* Providing the path to create a project is now deprecated.
* Client to use version 3 of the API.
* Change Qemu disk descriptions. Fixes #3035
* Edit only text mode config files
* Hide config import/export when configFiles attribute is empty
* Qemu disk interfaces must be set to "none" by default. Ref #3035
* Do not allow image to be configured on Qemu VM secondary slave disk if create config disk option is enabled.
* Add explicit option to automatically create or not the config disk. Off by default.
* Auxiliary console support for Qemu. Ref #2873 Improvements for auxiliary console support for Docker and Dynamips.
* Support to reset all console connections. Ref https://github.com/GNS3/gns3-server/issues/1619
* Support to reset links. Fixes https://github.com/GNS3/gns3-server/issues/1620
* Fix bug when recent files cannot be seen in the new project dialog.
* Wait for the controller to be online before allowing actions like creating or opening a project. Fixes #2907
* Show progress dialog immediately when connecting to server. Ref #2907
* QEMU config disk - enable QEMU config import/export
* Add total RAM, CPUs and disk size to servers summary as well as disk usage in percent. Fixes https://github.com/GNS3/gns3-server/issues/1532
* Resource constraints for Docker VMs.
* Support for "usage" for "Cloud" nodes. Fixes https://github.com/GNS3/gns3-gui/issues/2887 Allow "usage" for all builtin nodes (not exposed in Ui).
* Markdown support in project Readme. Fixes #2550 #2289 Allow project README to be edited from "File->Edit project". Fixes #2829
## 2.2.34 28/08/2022
* Upgrade dev dependencies
* Implement new option (Delete All) to contextual menu in "Console" dock. Fixes #3325
* Fix 2560x1440 resolution for Docker container
## 2.2.33.1 21/06/2022
* Match GNS3 server version
## 2.2.33 20/06/2022
* Upgrade sentry-sdk and psutil
* Check that node names for Qemu and Docker are valid
* Backport reset all console connections. Fixes #2072
* Add more video resolutions to Docker containers using VNC. Fixes #3329
* Add python_requires=">=3.4" in setup.py. Fixes #3326
* Only allow post release corrective versions of GUI and server to interact
* Allow minor versions of GUI and server to interact
* Update VirtViewer path. Fixes #3334
## 2.2.32 27/04/2022
* Use public DSNs for Sentry
* Fix exception when doubleclick on NAT node. Fixes #3312
* Fix "Apply" button in the "Preferences" dialog stays gray when templates/nodes are opened by double-click. Fixes #3307
* Add 'reset docks' in the view menu. Ref #3317
## 2.2.31 26/02/2022
* Install setuptools v59.6.0 when using Python 3.6
## 2.2.30 25/02/2022
* Set setuptools to v60.6.0
* Upgrade to pywin32 v303. Ref #3290
* Fix int() call. Ref #3283
* Fix QPoint() as unexpected type 'float'. Fixes #3283
* Fix painter.drawRect() has unexpected type 'float'. Fixes #3282
* Fix SpinBox.setValue() requires integer. Fixes #3281
## 2.2.29 08/01/2022
* Clear cache when opening symbol selection dialog. Fixes #3256
* Fix @ in username issue with HTTP authentication. Fixes #3275
* Use '//' operator instead of int()
* Fix create drawing item calls since mapToScene() returns a QPointF https://doc.qt.io/qt-5/qgraphicsview.html#mapToScene-4
* Fixed QPoint called with floats
## 2.2.28 15/12/2021
* Fixed drawLine called with float arguments
* Fixed dead VIX API link
## 2.2.27 12/11/2021
* Fix symbols in "Symbol selection" dialog are not placed in alphabetical order. Fixes #3245
* Fix links duplicates in topology summary. Fixes #3251
* chore : use --no-cache-dir flag to pip in dockerfiles to save space
## 2.2.26 08/10/2021
* Upgrade embedded Python to version 3.7 in Windows package
* Upgrade Visual C++ Redistributable for Visual Studio 2019 in Windows package
* Fix SSL support in Windows package
* Open "template configuration" dialog with double click on template name in "Preferences". Fixes #3239
* Only show "virtio" network adapter when legacy node is enabled. Fixes https://github.com/GNS3/gns3-gui/issues/1969
* Double-click on a template opens "template configuration" dialog. Fixes #3236
* Fix "Custom symbols" can't be unfolded after using "Filter" field. Fixes #3231
## 2.2.25 14/09/2021
* Fix menu disabled for modal dialogs on macOS. Fixes #3007
* Change method to display the recent files menu. Fixes #3007
* Fix bug when using empty port names for custom adapters. Fixes #3228
* Upgrade Qt to version 5.15.4 on macOS
* Fix mouse zoom-in/out step value is two times bigger than keyboard one. Fixes #3226
* Upgrade to Qt 5.15.4 on Windows. Ref #3210
* Fix issue with custom adapters at the node level. Fixes #3223
* Explicitly require setuptools, utils/get_resource.py imports pkg_resources
## 2.2.24 25/08/2021
* Fix incorrect Qemu binary selected when importing template. Fixes https://github.com/GNS3/gns3-gui/issues/3216
* Early support for Python3.10
* Bump pywin32 from 300 to 301
* Add PyQt5==5.12.3 for macOS build
## 2.2.23 05/08/2021
* Handle -no-kvm param deprecated in Qemu >= v5.2
* Support for invisible links. Fixes #2461
* Add kitty console application command line. Fixes #3203
* Add Windows Terminal profile as an option for Console Applications. Fixes #3193
## 2.2.22 10/06/2021
* Fix exception shown when GNS3 is started with empty config. Fixes #3188
* Add ZOC8 console terminal for macOS command line
* Link style support. Fixes https://github.com/GNS3/gns3-gui/issues/2461
* Fix charcoal theme. Ref #3137
* Fix issue when showing menu to select port. Fixes #3169
## 2.2.21 10/05/2021
* Fix issue with empty project variable name. Fixes #3162
* Downgrade to PyQt5 5.12.1. Fixes https://github.com/GNS3/gns3-gui/issues/3169
## 2.2.20 09/04/2021
* Fix project does not load anymore. Fixes #3140
* Do not connect to server while waiting for user to accept/reject SSL certificate. Fixes #3144
* Fix invalid server version check request. Fixes #3144
* Upgrade dependencies
* Add terminator as a predefined custom console option
## 2.2.19 05/03/2021
* No changes
## 2.2.18 16/02/2021
* SSL support.
* Remove the useless file "zoom-in (copy).svg". Fixes #3114
* Use HDD disk image as startup QEMU config disk
* Edit only text mode config files
* Hide config import/export when configFiles attribute is empty
* Qemu disk interfaces must be set to "none" by default. Ref #3035
* Do not allow image to be configured on Qemu VM secondary slave disk if create config disk option is enabled.
* Add explicit option to automatically create or not the config disk. Off by default.
* QEMU config disk support
## 2.2.17 04/12/2020
* Remove "-nographic" option by default for Qemu VM. Fixes #3094
* Fix app cannot start on macOS Big Sur. Ref #3037
* Require confirmation before stopping all devices.
## 2.2.16 05/11/2020
* Fix packets capture stops after some time. Fixes #3067
* Option to allocate or not the vCPUs and RAM settings for the GNS3 VM. Fixes https://github.com/GNS3/gns3-gui/issues/3069
## 2.2.15 07/10/2020
* Fix custom symbol not sent to remote controller when installing appliance
## 2.2.14 14/09/2020
* Improvements to add a new version of an appliance from wizard. Fixes #3002.
## 2.2.13 04/09/2020
* No changes
## 2.2.12 07/08/2020
* Downgrade psutil to version 5.6.7
* Fix log shows the GUI command line without spaces between its arguments. Fixes #3026
* Use server host is console host is equal to "0:0:0:0:0:0:0:0"
* Remove VMware promotion.
## 2.2.11 09/07/2020
* Try to fix "Recent project" selection not working. Ref #3007
* Fix debug entries shown twice in console window and double error messages with remote GNS3VM. Fixes #3010
* Fix deprecation warning. Ref #3009
* Fix tests on macOS. Ref #3009
* Fix sentry SDK is configured twice.
## 2.2.10 18/06/2020
* New fix for multi-device selection/deselection not working as expected with right click. Fixes #2986
* Optimize snap-to-grid code for drawing items. Fixes #2997
* Move jsonschema 2.6.0 requirement in build repository.
* Only use jsonschema 2.6.0 on Windows and macOS.
* Disable default integrations for sentry sdk.
## 2.2.9 04/06/2020
* Fix GUI doesn't detect another GUI on macOS. Fixes #2994
* Support to activate/deactive network connection state replication in Qemu.
* Option to reset or not all MAC addresses when exporting or duplicating a project.
* Fix Multi-device selection/deselection not working as expected with right click. Fixes #2986
* Replace Raven by Sentry SDK. Fixes https://github.com/GNS3/gns3-server/issues/1758
* Fix online help menu URL. Fixes #2984
* Require setuptools>=17.1 in setup.py. Ref https://github.com/GNS3/gns3-server/issues/1751 This is to support environmental markers. https://github.com/pypa/setuptools/blob/master/CHANGES.rst#171
* Update README. Ref https://github.com/GNS3/gns3-server/issues/1719
* Restore editReadme attribute which was removed in Change 'New export project wizard'
* Updated GUI pyqt files from Tab Order 'fixes' in "Tab Order in Preferences and Project Dialog #2872"
## 2.2.8 07/05/2020
* Default port set to 80 for server running in the GNS3 VM. Fixes #1737
* Make the Web UI the default page. Ref https://github.com/GNS3/gns3-server/issues/1737
* Fix "export portable project forgets contents of README". Fixes #1724
* Activate unified title and toolbar on MacOS. Fixes #2968
* Confirmation dialog for "console connect to all nodes". Fixes #2971
* Add "Resume all suspended links". Fixes #2858
* Revert "Change default path for SecureCRT. Fixes #2896"
* Remove @property from ConfigurationDialog(). Fixes #2819 #2965
* Use Environmental Markers to force jsonschema version. Fixes https://github.com/GNS3/gns3-gui/issues/2849 Version 3.2.0 with Python >= 3.8 Version 2.6.0 with Python < 3.8
* Use Environmental Markers to force jsonschema version 2.6.0 on Windows/macOS. Ref https://github.com/GNS3/gns3-gui/issues/2849
* Remove preferences dialog geometry restoration. Fixes #2807
* Fix unable to configure custom adapters for Qemu VMs. Fixes #2961
## 2.2.7 07/04/2020
* Fix VNC console template doesn't extract %i (Project UUID). Fixes #2960
* Fix contextual menu issues. Ref #2955
## 2.2.6 26/03/2020
* Prevent locked drawings to be deleted. Fixes https://github.com/GNS3/gns3-gui/issues/2948
* Fix issues with empty project variables. Fixes https://github.com/GNS3/gns3-gui/issues/2941
* Upgrade psutil to version 5.6.6 due to CVE-2019-18874 https://github.com/advisories/GHSA-qfc5-mcwq-26q8
* Use existing README.txt if existing when exporting portable project. Fixes https://github.com/GNS3/gns3-server/issues/1724
* Allow creation of a diskless Qemu VMs. Fixes #2939
* Re-enable "create new version" in appliance wizard. Fixes #2837
* Fix unable to load project from project library. Fixes #2932
* Fix some permission denied errors when loading remote project. Ref #2871 Fixes #2901
* Add 'Royal TS V5' to predefined console list
* Disallow invalid grid sized. Fixes #2908
* Check if hostname is blank. Fixes #2924
* Add nvme disk interface and fix scsi disk interface for Qemu VMs.
* Add latest Qemu nic models.
* Upgrade Qt version to 5.14.1. Ref #2778 #2903
## 2.2.5 09/01/2020
* Add gns3-gui.xml and update Linux icons paths & permissions. Ref #2919
## 2.2.4 08/01/2020
* Fix "Console to all nodes" doesn't open cloud objects with console configured. Fixes #2902
* Change default path for SecureCRT. Fixes #2896
* Add icons in setup.py Ref #2898
* Add remote viewer as a VNC console for Linux. Fixes #2913
## 2.2.3 12/11/2019
* Fix issue when binding on 0.0.0.0. Fixes #2892
* Allow double click on cloud with configured console to open session. Fixes #2894
* Officially support Python 3.8. Ref https://github.com/GNS3/gns3-gui/issues/2895
* Set psutil to version 5.6.3 in requirements.txt
## 2.2.2 04/11/2019
* Fix KeyError: 'spice+agent'. Fixes #2890

View File

@@ -1,22 +1,16 @@
# Run tests inside a container
FROM ubuntu:18.04
MAINTAINER GNS3 Team
#ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install -y --force-yes python3.6 python3-pyqt5 python3-pip python3-pyqt5.qtsvg python3-pyqt5.qtwebsockets python3.6-dev xvfb
RUN apt-get clean
ADD dev-requirements.txt /dev-requirements.txt
ADD requirements.txt /requirements.txt
RUN pip3 install -r /dev-requirements.txt
RUN pip3 install --no-cache-dir -r /dev-requirements.txt
ADD . /src
WORKDIR /src
CMD xvfb-run python3.6 -m pytest -vv

View File

@@ -3,7 +3,6 @@ include AUTHORS
include LICENSE
include MANIFEST.in
include requirements.txt
include tox.ini
recursive-include tests *
recursive-include gns3 *
recursive-include resources *

46
README.md Normal file
View File

@@ -0,0 +1,46 @@
# GNS3-gui
[![GitHub Actions tests](https://github.com/GNS3/gns3-gui/workflows/testing/badge.svg)](https://github.com/GNS3/gns3-gui/actions?query=workflow%3Atesting)
[![Latest PyPi version](https://img.shields.io/pypi/v/gns3-gui.svg)](https://pypi.python.org/pypi/gns3-gui)
[![Snyk scanning](https://snyk.io/test/github/GNS3/gns3-gui/badge.svg)](https://snyk.io/test/github/GNS3/gns3-gui)
## Installation
Please see the documentation on our [website](https://docs.gns3.com)
## Software dependencies
PyQt5 which is either part of the Linux distribution or installable from PyPi. The other Python dependencies are automatically installed during the GNS3 GUI installation and are listed in [requirements.txt](https://github.com/GNS3/gns3-gui/blob/3.0/requirements.txt>)
For connecting to nodes using Telnet, a Telnet client is required. On Linux that's a terminal emulator like xterm, gnome-terminal, konsole plus the telnet program. For connecting to nodes with a GUI, a VNC client is required, optionally a SPICE client can be used for Qemu nodes.
For using packet captures within GNS3, Wireshark should be installed. It's recommended, but if you don't need that functionality you can go without it.
## Development
If you want to update the interface, modify the .ui files using QT tools. And:
```shell
cd scripts
python build_pyqt.py
```
### Debugging
If you want to see the full logs in the internal shell you can type:
```shell
debug 2
```
Or start the app with --debug flag.
Due to the fact PyQT intercept you can use a web debugger for inspecting stuff:
https://github.com/Kozea/wdb
## Security issues
Please contact us at security@gns3.net

View File

@@ -1,47 +0,0 @@
GNS3-gui
========
.. image:: https://travis-ci.org/GNS3/gns3-gui.svg?branch=master
:target: https://travis-ci.org/GNS3/gns3-gui
.. image:: https://img.shields.io/pypi/v/gns3-gui.svg
:target: https://pypi.python.org/pypi/gns3-gui
GNS3 GUI repository.
Installation
------------
Please see https://docs.gns3.com/
Development
-------------
If you want to update the interface, modify the .ui files using QT tools. And:
.. code:: bash
cd scripts
python build_pyqt.py
Debug
"""""
If you want to see the full logs in the internal shell you can type:
.. code:: bash
debug 2
Or start the app with --debug flag.
Due to the fact PyQT intercept you can use a web debugger for inspecting stuff:
https://github.com/Kozea/wdb
Security issues
----------------
Please contact us using contact informations available here:
http://docs.gns3.com/1ON9JBXSeR7Nt2-Qum2o3ZX0GU86BZwlmNSUgvmqNWGY/index.html

View File

@@ -1,15 +1,16 @@
version: '{build}-{branch}'
image: Visual Studio 2017
image: Visual Studio 2022
platform: x64
environment:
PYTHON: "C:\\Python36-x64"
PYTHON: "C:\\Python37-x64"
DISTUTILS_USE_SDK: "1"
install:
- cinst nmap
- "%PYTHON%\\python.exe -m pip install -U pip setuptools" # upgrade pip & setuptools first
- "%PYTHON%\\python.exe -m pip install -r dev-requirements.txt"
- "%PYTHON%\\python.exe -m pip install -r win-requirements.txt"

View File

@@ -1,6 +1,5 @@
-rrequirements.txt
-r requirements.txt
pep8==1.7.0
pytest==4.4.1
pytest-pythonpath==0.7.3 # useful for running tests outside tox
pytest-timeout==1.3.3
pytest==7.2.0
flake8==5.0.4 # v5.0.4 is the last to support Python 3.7
pytest-timeout==2.1.0

View File

@@ -19,6 +19,7 @@ from .qt import QtCore
from .controller import Controller
from .local_config import LocalConfig
from .settings import GENERAL_SETTINGS
from .http_client_error import HttpClientError
import logging
@@ -49,7 +50,17 @@ class ApplianceManager(QtCore.QObject):
settings = LocalConfig.instance().loadSectionSettings("MainWindow", GENERAL_SETTINGS)
symbol_theme = settings["symbol_theme"]
if update is True:
self._controller.get("/appliances?update=yes&symbol_theme={}".format(symbol_theme), self._listAppliancesCallback, progressText="Downloading appliances from online registry...")
try:
self._controller.get(
"/appliances?update=yes&symbol_theme={}".format(symbol_theme),
self._listAppliancesCallback,
progress_text="Downloading appliances from online registry...",
wait=True,
timeout=300
)
except HttpClientError as e:
log.error(f"Error while getting appliances list: {e}")
return
else:
self._controller.get("/appliances?symbol_theme={}".format(symbol_theme), self._listAppliancesCallback)

View File

@@ -20,6 +20,7 @@ import sys
from .qt import QtWidgets, QtGui, QtCore
from gns3.utils import parse_version
from gns3.local_config import LocalConfig
from .version import __version__
import logging
@@ -37,7 +38,9 @@ class Application(QtWidgets.QApplication):
# only available starting Qt version 5.6
if hdpi:
if sys.platform.startswith("linux"):
log.warning("HDPI mode is enabled. HDPI support on Linux is not fully stable and GNS3 may crash depending of your version of Linux. To disabled HDPI mode please edit ~/.config/GNS3/gns3_gui.conf and set 'hdpi' to 'false'")
local_config_path = LocalConfig.instance().configFilePath()
log.warning("HDPI mode is enabled. HDPI support on Linux is not fully stable and GNS3 may crash depending of your version of Linux. "
f"To disabled HDPI mode please edit '{local_config_path}' and set 'hdpi' to 'false'")
self.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
self.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
else:

View File

@@ -37,6 +37,7 @@ class Compute:
self._password = None
self._cpu_usage_percent = None
self._memory_usage_percent = None
self._disk_usage_percent = None
self._capabilities = {"node_types": []}
self._last_error = None
@@ -202,6 +203,24 @@ class Compute:
return self._memory_usage_percent
def setDiskUsagePercent(self, usage):
"""
Sets the compute disk usage.
:returns: disk usage (integer)
"""
self._disk_usage_percent = usage
def diskUsagePercent(self):
"""
Returns the compute disk usage.
:param usage: disk usage (integer)
"""
return self._disk_usage_percent
def capabilities(self):
"""
Returns the compute capabilities

View File

@@ -15,7 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .qt import QtCore
from .qt import QtCore, QtWidgets
from .compute import Compute
from .controller import Controller
@@ -50,11 +50,11 @@ class ComputeManager(QtCore.QObject):
# No need to refresh via an API call if we received fresh data from the notification feed
self._last_computes_refresh = datetime.datetime.now().timestamp()
self._timer = QtCore.QTimer()
self._timer.setInterval(1000)
self._refreshingComputes = False
self._timer.timeout.connect(self._refreshComputesSlot)
self._timer.start()
# self._timer = QtCore.QTimer()
# self._timer.setInterval(1000)
# self._timer.timeout.connect(self._refreshComputesSlot)
# self._timer.start()
def _refreshComputesSlot(self):
"""
@@ -66,7 +66,7 @@ class ComputeManager(QtCore.QObject):
if self._controller.connected() and datetime.datetime.now().timestamp() - self._last_computes_refresh > 1:
self._last_computes_refresh = datetime.datetime.now().timestamp()
self._refreshingComputes = True
self._controller.get("/computes", self._listComputesCallback, showProgress=False, timeout=30)
self._controller.get("/computes", self._listComputesCallback, show_progress=False, timeout=30)
def _controllerConnectedSlot(self):
"""
@@ -75,11 +75,11 @@ class ComputeManager(QtCore.QObject):
if self._controller.connected():
self._refreshingComputes = True
self._controller.get("/computes", self._listComputesCallback, showProgress=False, timeout=30)
self._controller.get("/computes", self._listComputesCallback, show_progress=False, timeout=30)
def _controllerDisconnectedSlot(self):
"""
Called when disconnected from a compute.
Called when disconnected from the controller.
"""
for compute_id in list(self._computes):
@@ -96,8 +96,9 @@ class ComputeManager(QtCore.QObject):
log.error("Error while getting compute list: {}".format(result["message"]))
return
for compute in result:
self.computeDataReceivedCallback(compute)
if result:
for compute in result:
self.computeDataReceivedCallback(compute)
def computeDataReceivedCallback(self, compute):
"""
@@ -113,15 +114,17 @@ class ComputeManager(QtCore.QObject):
self._computes[compute_id] = Compute(compute_id)
self._computes[compute_id].setName(compute["name"])
self._computes[compute_id].setConnected(compute["connected"])
self._computes[compute_id].setProtocol(compute["protocol"])
self._computes[compute_id].setHost(compute["host"])
self._computes[compute_id].setPort(compute["port"])
self._computes[compute_id].setUser(compute["user"])
self._computes[compute_id].setCpuUsagePercent(compute["cpu_usage_percent"])
self._computes[compute_id].setMemoryUsagePercent(compute["memory_usage_percent"])
self._computes[compute_id].setCapabilities(compute["capabilities"])
self._computes[compute_id].setLastError(compute.get("last_error"))
if "connected" in compute:
self._computes[compute_id].setConnected(compute["connected"])
self._computes[compute_id].setCpuUsagePercent(compute["cpu_usage_percent"])
self._computes[compute_id].setMemoryUsagePercent(compute["memory_usage_percent"])
self._computes[compute_id].setDiskUsagePercent(compute["disk_usage_percent"])
self._computes[compute_id].setCapabilities(compute["capabilities"])
self._computes[compute_id].setLastError(compute.get("last_error"))
if new_node:
self.created_signal.emit(compute_id)
@@ -208,6 +211,20 @@ class ComputeManager(QtCore.QObject):
self.created_signal.emit(compute_id)
return self._computes[compute_id]
def connectToCompute(self, compute_id):
"""
Connect to a compute
"""
self._controller.post(f"/computes/{compute_id}/connect", callback=self._computeConnectCallback)
def _computeConnectCallback(self, result, error=False, **kwargs):
if error and "message" in result:
from gns3.main_window import MainWindow
parent = MainWindow.instance()
QtWidgets.QMessageBox.critical(parent, "Remote compute", result.get("message"))
def deleteCompute(self, compute_id):
"""
Deletes a compute by ID
@@ -245,10 +262,16 @@ class ComputeManager(QtCore.QObject):
for compute in computes:
if compute.id() not in self._computes:
log.debug("Create compute %s", compute.id())
self._controller.post("/computes", None, body=compute.__json__())
params = {"connect": True}
self._controller.post("/computes", callback=self._computeCreatedCallback, body=compute.__json__(), params=params)
self._computes[compute.id()] = compute
self.created_signal.emit(compute.id())
def _computeCreatedCallback(self, result, error=False, **kwargs):
if error:
log.error(result.get("message"))
@staticmethod
def reset():
ComputeManager._instance = None

View File

@@ -23,6 +23,8 @@ from .qt import QtGui, QtCore, QtWidgets
from .compute_manager import ComputeManager
from .topology import Topology
from .node import Node
from .utils import human_size
from .utils.get_icon import get_icon
import logging
log = logging.getLogger(__name__)
@@ -43,9 +45,16 @@ class ComputeItem(QtWidgets.QTreeWidgetItem):
self._compute = compute
self._parent = parent
self._status = "unknown"
self._refreshStatusSlot()
def getCompute(self):
return self._compute
def setCompute(self, compute):
self._compute = compute
def _refreshStatusSlot(self):
"""
Changes the icon to show the node status (started, stopped etc.)
@@ -58,14 +67,20 @@ class ComputeItem(QtWidgets.QTreeWidgetItem):
text = self._compute.name()
if self._compute.cpuUsagePercent() is not None:
text = "{} CPU {}%, RAM {}%".format(text, self._compute.cpuUsagePercent(), self._compute.memoryUsagePercent())
text = "{} CPU {}%, RAM {}%, DISK {}%".format(text,
self._compute.cpuUsagePercent(),
self._compute.memoryUsagePercent(),
self._compute.diskUsagePercent())
self.setText(0, text)
if self._compute.connected():
self._status = "connected"
self.setToolTip(0, "Server {} version {} running on {}".format(self._compute.name(),
self._compute.capabilities().get("version", "n/a"),
self._compute.capabilities().get("platform", "")))
self.setToolTip(0, "Server {} v{} running on {} (CPUs={} / RAM={} / DISK={})".format(self._compute.name(),
self._compute.capabilities().get("version", "n/a"),
self._compute.capabilities().get("platform", ""),
self._compute.capabilities().get("cpus", 0),
human_size(self._compute.capabilities().get("memory", 0)),
human_size(self._compute.capabilities().get("disk_size", 0))))
if usage is None or (self._compute.cpuUsagePercent() < 90 and self._compute.memoryUsagePercent() < 90):
self.setIcon(0, QtGui.QIcon(':/icons/led_green.svg'))
else:
@@ -111,13 +126,44 @@ class ComputeSummaryView(QtWidgets.QTreeWidget):
def __init__(self, parent):
super().__init__(parent)
self._computes = {}
self._compute_items = {}
ComputeManager.instance().created_signal.connect(self._computeAddedSlot)
ComputeManager.instance().updated_signal.connect(self._computeUpdatedSlot)
ComputeManager.instance().deleted_signal.connect(self._computeRemovedSlot)
for compute in ComputeManager.instance().computes():
self._computeAddedSlot(compute.id())
def contextMenuEvent(self, event):
"""
Handles all context menu events.
:param event: QContextMenuEvent instance
"""
self._showContextualMenu(event.globalPos())
def _showContextualMenu(self, pos):
item = self.currentItem()
if item:
compute = item.getCompute()
if not compute.connected():
menu = QtWidgets.QMenu()
connect_action = QtWidgets.QAction("Connect to server", menu)
connect_action.setIcon(get_icon("start.svg"))
connect_action.triggered.connect(lambda: ComputeManager.instance().connectToCompute(compute.id()))
menu.addAction(connect_action)
menu.exec_(pos)
def _computeConnectSlot(self, compute_id):
"""
:param compute_id:
:return:
"""
ComputeManager.instance().connectToCompute(compute_id)
def _computeAddedSlot(self, compute_id):
"""
Called when a compute is added to the list of computes
@@ -128,7 +174,7 @@ class ComputeSummaryView(QtWidgets.QTreeWidget):
compute = ComputeManager.instance().getCompute(compute_id)
if ComputeManager.instance().computeIsTheRemoteGNS3VM(compute):
return
self._computes[compute_id] = ComputeItem(self, compute)
self._compute_items[compute_id] = ComputeItem(self, compute)
def _computeUpdatedSlot(self, compute_id):
"""
@@ -137,13 +183,14 @@ class ComputeSummaryView(QtWidgets.QTreeWidget):
:params url: URL of the compute
"""
if compute_id in self._computes:
if compute_id in self._compute_items:
compute = ComputeManager.instance().getCompute(compute_id)
# We hide the remote GNS3 VM
if ComputeManager.instance().computeIsTheRemoteGNS3VM(compute):
self._computeRemovedSlot(compute_id)
else:
self._computes[compute_id]._refreshStatusSlot()
self._compute_items[compute_id].setCompute(compute)
self._compute_items[compute_id]._refreshStatusSlot()
else:
self._computeAddedSlot(compute_id)
@@ -154,6 +201,6 @@ class ComputeSummaryView(QtWidgets.QTreeWidget):
:params url: URL of the compute
"""
if compute_id in self._computes:
self.takeTopLevelItem(self.indexOfTopLevelItem(self._computes[compute_id]))
del self._computes[compute_id]
if compute_id in self._compute_items:
self.takeTopLevelItem(self.indexOfTopLevelItem(self._compute_items[compute_id]))
del self._compute_items[compute_id]

View File

@@ -223,17 +223,10 @@ class ConsoleCmd(cmd.Cmd):
level = int(args[0])
if level == 0:
print("Deactivating debugging")
for handler in root.handlers:
if isinstance(handler, logging.StreamHandler):
root.removeHandler(handler)
root.setLevel(logging.INFO)
else:
root.addHandler(logging.StreamHandler(sys.stdout))
if level == 1:
print("Activating debugging")
else:
print("Activating full debugging")
root.setLevel(logging.DEBUG)
print("Activating debugging")
root.setLevel(logging.DEBUG)
from .main_window import MainWindow
MainWindow.instance().setSettings({"debug_level": level})
else:

View File

@@ -22,7 +22,7 @@ import inspect
import datetime
import platform
from .qt import QtCore
from .qt import QtCore, QtWidgets
from .topology import Topology
from .version import __version__
from .console_cmd import ConsoleCmd
@@ -109,6 +109,29 @@ class ConsoleView(PyCutExt, ConsoleCmd):
self.stdout = sys.stdout
self._topology = Topology.instance()
def contextMenuEvent(self, event):
"""
Handles all context menu events.
:param event: QContextMenuEvent instance
"""
menu = self.createStandardContextMenu()
delete_all_action = QtWidgets.QAction("Delete All", menu)
delete_all_action.triggered.connect(self._deleteAllActionSlot)
menu.addAction(delete_all_action)
menu.exec_(event.globalPos());
def _deleteAllActionSlot(self):
"""
Delete all action slot
"""
self.clear()
self.write(self.prompt)
self.lines = []
self._clearLine()
def _writeMessageSlot(self, message, level):
"""
Write a message in the console.

View File

@@ -21,11 +21,12 @@ import tempfile
import json
import pathlib
from .qt import QtCore, QtNetwork, QtGui, QtWidgets, QtWebSockets, qpartial, qslot
from .qt import QtCore, QtGui, QtWebSockets, qpartial, qslot
from .symbol import Symbol
from .local_server_config import LocalServerConfig
from .settings import LOCAL_SERVER_SETTINGS
from .local_config import LocalConfig
from .settings import CONTROLLER_SETTINGS
from gns3.utils import parse_version
from gns3.http_client import HTTPClient
import logging
log = logging.getLogger(__name__)
@@ -40,6 +41,7 @@ class Controller(QtCore.QObject):
disconnected_signal = QtCore.Signal()
connection_failed_signal = QtCore.Signal()
project_list_updated_signal = QtCore.Signal()
image_list_updated_signal = QtCore.Signal()
def __init__(self):
@@ -54,16 +56,47 @@ class Controller(QtCore.QObject):
self._error_dialog = None
self._display_error = True
self._projects = []
self._images = []
self._websocket = QtWebSockets.QWebSocket()
# If we do multiple call in order to download the same symbol we queue them
self._static_asset_download_queue = {}
self._loadSettings()
def settings(self):
"""
Returns the graphics view settings.
:returns: settings dictionary
"""
return self._settings
def _loadSettings(self):
"""
Loads the settings from the persistent settings file.
"""
self._settings = LocalConfig.instance().loadSectionSettings(self.__class__.__name__, CONTROLLER_SETTINGS)
def setSettings(self, new_settings):
"""
Set new controller settings.
:param new_settings: settings dictionary
"""
# save the settings
self._settings.update(new_settings)
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
def host(self):
return self._http_client.host()
def version(self):
return self._version
def isRemote(self):
@@ -71,8 +104,7 @@ class Controller(QtCore.QObject):
:returns Boolean: True if the controller is remote
"""
settings = LocalServerConfig.instance().loadSettings("Server", LOCAL_SERVER_SETTINGS)
return not settings["auto_start"]
return self._settings["remote"]
def connecting(self):
"""
@@ -102,10 +134,8 @@ class Controller(QtCore.QObject):
self._http_client = http_client
if self._http_client:
if self.isRemote():
self._http_client.setMaxTimeDifferenceBetweenQueries(120)
self._http_client.connection_connected_signal.connect(self._httpClientConnectedSlot)
self._http_client.connection_disconnected_signal.connect(self._httpClientDisconnectedSlot)
self._http_client.connected_signal.connect(self._httpClientConnectedSlot)
self._http_client.disconnected_signal.connect(self._httpClientDisconnectedSlot)
self._connectingToServer()
def getHttpClient(self):
@@ -123,6 +153,14 @@ class Controller(QtCore.QObject):
self._display_error = val
self._first_error = True
def connect(self):
"""
Connect to controller
"""
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
def _connectingToServer(self):
"""
Connection process as started
@@ -130,41 +168,16 @@ class Controller(QtCore.QObject):
self._connected = False
self._connecting = True
self.get('/version', self._versionGetSlot)
self.httpClient().connectToServer()
def _httpClientDisconnectedSlot(self):
if self._connected:
self._connected = False
self.disconnected_signal.emit()
self._connectingToServer()
self.stopListenNotifications()
def _versionGetSlot(self, result, error=False, **kwargs):
"""
Called after the initial version get
"""
if error:
if self._first_error:
self._connecting = False
self.connection_failed_signal.emit()
if "message" in result and self._display_error:
self._error_dialog = QtWidgets.QMessageBox(self.parent())
self._error_dialog.setWindowModality(QtCore.Qt.ApplicationModal)
self._error_dialog.setWindowTitle("Connection to server")
self._error_dialog.setText("Error when connecting to the GNS3 server:\n{}".format(result["message"]))
self._error_dialog.setIcon(QtWidgets.QMessageBox.Critical)
self._error_dialog.show()
# Try to connect again in 5 seconds
QtCore.QTimer.singleShot(5000, qpartial(self.get, '/version', self._versionGetSlot, showProgress=self._first_error))
self._first_error = False
else:
self._first_error = True
if self._error_dialog:
self._error_dialog.reject()
self._error_dialog = None
self._version = result.get("version")
def _httpClientConnectedSlot(self):
if not self._connected:
@@ -175,16 +188,16 @@ class Controller(QtCore.QObject):
self._startListenNotifications()
def post(self, *args, **kwargs):
return self.createHTTPQuery("POST", *args, **kwargs)
return self.request("POST", *args, **kwargs)
def get(self, *args, **kwargs):
return self.createHTTPQuery("GET", *args, **kwargs)
return self.request("GET", *args, **kwargs)
def put(self, *args, **kwargs):
return self.createHTTPQuery("PUT", *args, **kwargs)
return self.request("PUT", *args, **kwargs)
def delete(self, *args, **kwargs):
return self.createHTTPQuery("DELETE", *args, **kwargs)
return self.request("DELETE", *args, **kwargs)
def getCompute(self, path, compute_id, *args, **kwargs):
"""
@@ -220,31 +233,13 @@ class Controller(QtCore.QObject):
return compute_id
return compute_id
def getEndpoint(self, path, compute_id, *args, **kwargs):
"""
API post on a specific compute
"""
compute_id = self.__fix_compute_id(compute_id)
path = "/computes/endpoint/{}{}".format(compute_id, path)
return self.get(path, *args, **kwargs)
def putCompute(self, path, compute_id, *args, **kwargs):
"""
API put on a specific compute
"""
compute_id = self.__fix_compute_id(compute_id)
path = "/computes/{}{}".format(compute_id, path)
return self.put(path, *args, **kwargs)
def createHTTPQuery(self, method, path, *args, **kwargs):
def request(self, method, path, *args, **kwargs):
"""
Forward the query to the HTTP client or controller depending of the path
"""
if self._http_client:
return self._http_client.createHTTPQuery(method, path, *args, **kwargs)
return self._http_client.sendRequest(method, path, *args, **kwargs)
@staticmethod
def instance():
@@ -277,9 +272,10 @@ class Controller(QtCore.QObject):
self._static_asset_download_queue[path].append((callback, fallback, ))
else:
self._static_asset_download_queue[path] = [(callback, fallback, )]
self._http_client.createHTTPQuery("GET", url, qpartial(self._getStaticCallback, url, path))
self._http_client.sendRequest("GET", url, qpartial(self._getStaticCallback, url, path), raw=True)
def _getStaticCallback(self, url, path, result, error=False, **kwargs):
def _getStaticCallback(self, url, path, result, error=False, raw_body=None, **kwargs):
if path not in self._static_asset_download_queue:
return
@@ -295,7 +291,7 @@ class Controller(QtCore.QObject):
return
try:
with open(path, "wb+") as f:
f.write(raw_body)
f.write(result)
except OSError as e:
log.error("Can't write to {}: {}".format(path, str(e)))
return
@@ -359,9 +355,14 @@ class Controller(QtCore.QObject):
def uploadSymbol(self, symbol_id, path):
self.post("/symbols/" + symbol_id + "/raw",
qpartial(self._finishSymbolUpload, path),
body=pathlib.Path(path), progressText="Uploading {}".format(symbol_id), timeout=None)
self.post(
"/symbols/" + symbol_id + "/raw",
qpartial(self._finishSymbolUpload, path),
body=pathlib.Path(path),
progress_text="Uploading {}".format(symbol_id),
timeout=None,
wait=True
)
def _finishSymbolUpload(self, path, result, error=False, **kwargs):
@@ -402,27 +403,39 @@ class Controller(QtCore.QObject):
def projects(self):
return self._projects
@qslot
def refreshImageList(self, *args):
self.get("/images", self._imageListCallback)
def _imageListCallback(self, result, error=False, **kwargs):
if not error:
self._images = result
self.image_list_updated_signal.emit()
def images(self):
return self._images
def _startListenNotifications(self):
if not self.connected():
return
# Due to bug in Qt on some version we need a dedicated network manager
self._notification_network_manager = QtNetwork.QNetworkAccessManager()
self._notification_stream = None
# Qt websocket before Qt 5.6 doesn't support auth
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.6.0") or parse_version(QtCore.PYQT_VERSION_STR) < parse_version("5.6.0"):
self._notification_stream = Controller.instance().createHTTPQuery("GET", "/notifications", self._endListenNotificationCallback,
downloadProgressCallback=self._event_received,
networkManager=self._notification_network_manager,
timeout=None,
showProgress=False,
ignoreErrors=True)
self._notification_stream = Controller.instance().request(
"GET",
"/notifications",
self._endListenNotificationCallback,
download_progress_callback=self._event_received,
timeout=None,
show_progress=False
)
else:
self._notification_stream = self._http_client.connectWebSocket(self._websocket, "/notifications/ws")
self._notification_stream.textMessageReceived.connect(self._websocket_event_received)
self._notification_stream.error.connect(self._websocket_error)
self._notification_stream.sslErrors.connect(self._sslErrorsSlot)
def stopListenNotifications(self):
if self._notification_stream:
@@ -430,7 +443,6 @@ class Controller(QtCore.QObject):
stream = self._notification_stream
self._notification_stream = None
stream.abort()
self._notification_network_manager = None
def _endListenNotificationCallback(self, result, error=False, **kwargs):
"""
@@ -444,8 +456,12 @@ class Controller(QtCore.QObject):
def _websocket_error(self, error):
if self._notification_stream:
log.error("Websocket notification stream error: {}".format(self._notification_stream.errorString()))
self._notification_stream = None
self._startListenNotifications()
self.stopListenNotifications()
@qslot
def _sslErrorsSlot(self, ssl_errors):
self._http_client.handleSslError(self._notification_stream, ssl_errors)
@qslot
def _websocket_event_received(self, event):

View File

@@ -16,19 +16,18 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import psutil
import os
import platform
import struct
import distro
try:
import raven
from raven.transport.http import HTTPTransport
RAVEN_AVAILABLE = True
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
SENTRY_SDK_AVAILABLE = True
except ImportError:
# raven is not installed with deb package in order to simplify packaging
RAVEN_AVAILABLE = False
# Sentry SDK is not installed with deb package in order to simplify packaging
SENTRY_SDK_AVAILABLE = False
from .utils.get_resource import get_resource
from .version import __version__, __version_info__
@@ -52,66 +51,67 @@ class CrashReport:
Report crash to a third party service
"""
DSN = "https://dbedb95015d948b3b38917d7ac01e15b:1fcb50016b474c12b14c53d2b83eeabc@sentry.io/38506"
if hasattr(sys, "frozen"):
cacert = get_resource("cacert.pem")
if cacert is not None and os.path.isfile(cacert):
DSN += "?ca_certs={}".format(cacert)
else:
log.warning("The SSL certificate bundle file '{}' could not be found".format(cacert))
DSN = "https://e53718a5b9234e56a2fd3634e6fa07c9@o19455.ingest.sentry.io/38506"
_instance = None
def __init__(self):
# We don't want sentry making noise if an error is catched when you don't have internet
# We don't want sentry making noise if an error is caught when we don't have internet
sentry_errors = logging.getLogger('sentry.errors')
sentry_errors.disabled = True
sentry_uncaught = logging.getLogger('sentry.errors.uncaught')
sentry_uncaught.disabled = True
self._sentry_initialized = False
def captureException(self, exception, value, tb):
from .local_server import LocalServer
from .local_config import LocalConfig
from .controller import Controller
from .compute_manager import ComputeManager
if SENTRY_SDK_AVAILABLE:
cacert = None
if hasattr(sys, "frozen"):
cacert_resource = get_resource("cacert.pem")
if cacert_resource is not None and os.path.isfile(cacert_resource):
cacert = cacert_resource
else:
log.error("The SSL certificate bundle file '{}' could not be found".format(cacert_resource))
local_server = LocalServer.instance().localServerSettings()
if local_server["report_errors"]:
if not RAVEN_AVAILABLE:
return
# Don't send log records as events.
sentry_logging = LoggingIntegration(level=logging.INFO, event_level=None)
if os.path.exists(LocalConfig.instance().runAsRootPath()):
log.warning("User has run application as root. Crash reports are disabled.")
sys.exit(1)
return
sentry_sdk.init(dsn=CrashReport.DSN,
release=__version__,
ca_certs=cacert,
default_integrations=False,
integrations=[sentry_logging])
if os.path.exists(".git"):
log.warning("A .git directory exist crash report is turn off for developers. Instant exit")
sys.exit(1)
return
if hasattr(exception, "fingerprint"):
client = raven.Client(CrashReport.DSN, release=__version__, fingerprint=['{{ default }}', exception.fingerprint], transport=HTTPTransport)
else:
client = raven.Client(CrashReport.DSN, release=__version__, transport=HTTPTransport)
context = {
tags = {
"os:name": platform.system(),
"os:release": platform.release(),
"os:win_32": " ".join(platform.win32_ver()),
"os:mac": "{} {}".format(platform.mac_ver()[0], platform.mac_ver()[2]),
"os:linux": " ".join(distro.linux_distribution()),
"os:linux": distro.name(pretty=True),
}
self._add_qt_information(tags)
with sentry_sdk.configure_scope() as scope:
for key, value in tags.items():
scope.set_tag(key, value)
extra_context = {
"python:version": "{}.{}.{}".format(sys.version_info[0],
sys.version_info[1],
sys.version_info[2]),
"python:bit": struct.calcsize("P") * 8,
"python:encoding": sys.getdefaultencoding(),
"python:frozen": "{}".format(hasattr(sys, "frozen")),
"python:frozen": "{}".format(hasattr(sys, "frozen"))
}
# extra controller and compute information
extra_context = {"controller:version": Controller.instance().version(),
"controller:host": Controller.instance().host(),
"controller:connected": Controller.instance().connected()}
from .controller import Controller
from .compute_manager import ComputeManager
extra_context["controller:version"] = Controller.instance().version()
extra_context["controller:host"] = Controller.instance().host()
extra_context["controller:connected"] = Controller.instance().connected()
for index, compute in enumerate(ComputeManager.instance().computes()):
extra_context["compute{}:id".format(index)] = compute.id()
extra_context["compute{}:name".format(index)] = compute.name(),
@@ -120,27 +120,48 @@ class CrashReport:
extra_context["compute{}:platform".format(index)] = compute.capabilities().get("platform")
extra_context["compute{}:version".format(index)] = compute.capabilities().get("version")
context = self._add_qt_information(context)
client.tags_context(context)
client.extra_context(extra_context)
try:
report = client.captureException((exception, value, tb))
except Exception as e:
log.error("Can't send crash report to Sentry: {}".format(e))
return
log.debug("Crash report sent with event ID: {}".format(client.get_ident(report)))
with sentry_sdk.configure_scope() as scope:
for key, value in extra_context.items():
scope.set_extra(key, value)
def captureException(self, exception, value, tb):
from .local_server import LocalServer
from .local_config import LocalConfig
local_server = LocalServer.instance().localServerSettings()
if local_server["report_errors"]:
if not SENTRY_SDK_AVAILABLE:
log.warning("Cannot capture exception: Sentry SDK is not available")
return
if os.path.exists(LocalConfig.instance().runAsRootPath()):
log.warning("User is running application as root. Crash reports disabled.")
return
if not hasattr(sys, "frozen") and os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".git")):
log.warning(".git directory detected, crash reporting is turned off for developers.")
return
try:
error = (exception, value, tb)
sentry_sdk.capture_exception(error=error)
log.info("Crash report sent with event ID: {}".format(sentry_sdk.last_event_id()))
except Exception as e:
log.warning("Can't send crash report to Sentry: {}".format(e))
def _add_qt_information(self, tags):
def _add_qt_information(self, context):
try:
from .qt import QtCore
from .qt import sip
except ImportError:
return context
context["psutil:version"] = psutil.__version__
context["pyqt:version"] = QtCore.PYQT_VERSION_STR
context["qt:version"] = QtCore.QT_VERSION_STR
context["sip:version"] = sip.SIP_VERSION_STR
return context
return tags
tags["pyqt:version"] = QtCore.PYQT_VERSION_STR
tags["qt:version"] = QtCore.QT_VERSION_STR
tags["sip:version"] = sip.SIP_VERSION_STR
return tags
@classmethod
def instance(cls):

View File

@@ -16,6 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from ..qt import sip
import shutil
@@ -29,7 +30,7 @@ from ..registry.registry import Registry
from ..registry.config import Config
from ..registry.appliance_to_template import ApplianceToTemplate
from ..registry.image import Image
from ..utils import human_filesize
from ..utils import human_size
from ..utils.wait_for_lambda_worker import WaitForLambdaWorker
from ..utils.progress_dialog import ProgressDialog
from ..compute_manager import ComputeManager
@@ -52,7 +53,6 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
self.setupUi(self)
self._refreshing = False
self._server_check = False
self._template_created = False
self._path = path
@@ -72,12 +72,15 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
self.uiCreateVersionPushButton.clicked.connect(self._createVersionPushButtonClickedSlot)
self.allowCustomFiles.clicked.connect(self._allowCustomFilesChangedSlot)
#FIXME: deactivate the create version feature (confusing and maybe not necessary, TBD)
self.uiCreateVersionPushButton.hide()
# directories where to search for images
images_directories = list()
# add the current directory
if hasattr(sys, "frozen"):
images_directories.append(os.path.dirname(os.path.abspath(sys.executable)))
else:
images_directories.append(os.path.abspath(os.curdir))
for emulator in ("QEMU", "IOU", "DYNAMIPS"):
emulator_images_dir = ImageManager.instance().getDirectoryForType(emulator)
if os.path.exists(emulator_images_dir):
@@ -103,9 +106,6 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
# customize the server selection
self.uiRemoteRadioButton.toggled.connect(self._remoteServerToggledSlot)
if hasattr(self, "uiVMRadioButton"):
self.uiVMRadioButton.toggled.connect(self._vmToggledSlot)
self.uiLocalRadioButton.toggled.connect(self._localToggledSlot)
if Controller.instance().isRemote():
self.uiLocalRadioButton.setText("Install the appliance on the main server")
@@ -139,7 +139,12 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
# add symbol
if self._appliance["category"] == "guest":
symbol = ":/symbols/computer.svg"
if self._appliance.emulator() == "docker":
symbol = ":/symbols/docker_guest.svg"
elif self._appliance.emulator() == "qemu":
symbol = ":/symbols/qemu_guest.svg"
else:
symbol = ":/symbols/computer.svg"
else:
symbol = ":/symbols/{}.svg".format(self._appliance["category"])
self.page(page_id).setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(symbol))
@@ -147,21 +152,6 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
if self.page(page_id) == self.uiServerWizardPage:
Controller.instance().getSymbols(self._getSymbolsCallback)
if "qemu" in self._appliance:
emulator_type = "qemu"
elif "iou" in self._appliance:
emulator_type = "iou"
elif "docker" in self._appliance:
emulator_type = "docker"
elif "dynamips" in self._appliance:
emulator_type = "dynamips"
else:
QtWidgets.QMessageBox.warning(self, "Appliance", "Could not determine the emulator type")
is_mac = ComputeManager.instance().localPlatform().startswith("darwin")
is_win = ComputeManager.instance().localPlatform().startswith("win")
self.uiRemoteServersComboBox.clear()
if len(ComputeManager.instance().remoteComputes()) == 0:
self.uiRemoteRadioButton.setEnabled(False)
@@ -170,66 +160,27 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
for compute in ComputeManager.instance().remoteComputes():
self.uiRemoteServersComboBox.addItem(compute.name(), compute)
if not ComputeManager.instance().vmCompute():
self.uiVMRadioButton.setEnabled(False)
#if ComputeManager.instance().localPlatform() is None:
# self.uiLocalRadioButton.setEnabled(False)
if ComputeManager.instance().localPlatform() is None:
self.uiLocalRadioButton.setEnabled(False)
elif is_mac or is_win:
if emulator_type == "qemu":
# disallow usage of the local server because Qemu has issues on OSX and Windows
if not LocalConfig.instance().experimental():
self.uiLocalRadioButton.setEnabled(False)
elif emulator_type != "dynamips":
self.uiLocalRadioButton.setEnabled(False)
if ComputeManager.instance().vmCompute():
self.uiVMRadioButton.setChecked(True)
elif ComputeManager.instance().localCompute() and self.uiLocalRadioButton.isEnabled():
if ComputeManager.instance().localCompute() and self.uiLocalRadioButton.isEnabled():
self.uiLocalRadioButton.setChecked(True)
elif self.uiRemoteRadioButton.isEnabled():
self.uiRemoteRadioButton.setChecked(True)
else:
self.uiRemoteRadioButton.setChecked(False)
if is_mac or is_win:
if not self.uiRemoteRadioButton.isEnabled() and not self.uiVMRadioButton.isEnabled() and not self.uiLocalRadioButton.isEnabled():
QtWidgets.QMessageBox.warning(self, "GNS3 VM", "The GNS3 VM is not available, please configure the GNS3 VM before adding a new appliance.")
elif self.page(page_id) == self.uiFilesWizardPage:
if Controller.instance().isRemote() or self._compute_id != "local":
self._registry.getRemoteImageList(self._appliance.emulator(), self._compute_id)
else:
self.images_changed_signal.emit()
elif self.page(page_id) == self.uiQemuWizardPage:
if self._appliance['qemu'].get('kvm', 'require') == 'require':
self._server_check = False
Qemu.instance().getQemuCapabilitiesFromServer(self._compute_id, qpartial(self._qemuServerCapabilitiesCallback))
else:
self._server_check = True
Qemu.instance().getQemuBinariesFromServer(self._compute_id, qpartial(self._getQemuBinariesFromServerCallback), [self._appliance["qemu"]["arch"]])
elif self.page(page_id) == self.uiUsageWizardPage:
self.uiUsageTextEdit.setText("The template will be available in the {} category.\n\n{}".format(self._appliance["category"].replace("_", " "), self._appliance.get("usage", "")))
def _qemuServerCapabilitiesCallback(self, result, error=None, *args, **kwargs):
"""
Check if the server supports KVM or not
"""
if error is None and "kvm" in result and self._appliance["qemu"]["arch"] in result["kvm"]:
self._server_check = True
else:
if error:
msg = result["message"]
else:
msg = "The selected server does not support KVM. A Linux server or the GNS3 VM running in VMware is required."
QtWidgets.QMessageBox.critical(self, "KVM support", msg)
self._server_check = False
def _uiServerWizardPage_isComplete(self):
return self.uiRemoteRadioButton.isEnabled() or self.uiVMRadioButton.isEnabled() or self.uiLocalRadioButton.isEnabled()
return self.uiRemoteRadioButton.isEnabled() or self.uiLocalRadioButton.isEnabled()
def _imageUploadedCallback(self, result, error=False, context=None, **kwargs):
if context is None:
@@ -350,7 +301,7 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
size += image.get("filesize", 0)
image_widget = QtWidgets.QTreeWidgetItem([image["filename"],
human_filesize(image.get("filesize", 0)),
human_size(image.get("filesize", 0)),
image["status"]])
if image["status"] == "Missing":
image_widget.setForeground(2, QtGui.QBrush(QtGui.QColor("red")))
@@ -375,7 +326,7 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
expand = False
top.setForeground(2, QtGui.QBrush(QtGui.QColor("green")))
top.setData(1, QtCore.Qt.DisplayRole, human_filesize(size))
top.setData(1, QtCore.Qt.DisplayRole, human_size(size))
top.setData(2, QtCore.Qt.DisplayRole, status)
top.setData(0, QtCore.Qt.UserRole, version)
top.setData(2, QtCore.Qt.UserRole, self._appliance)
@@ -478,8 +429,24 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
Allow user to create a new version of an appliance
"""
new_version, ok = QtWidgets.QInputDialog.getText(self, "Creating a new version", "Creating a new version allows to import unknown files to use with this appliance.\nPlease share your experience on the GNS3 community if this version works.\n\nVersion name:", QtWidgets.QLineEdit.Normal)
current = self.uiApplianceVersionTreeWidget.currentItem()
if current is None:
QtWidgets.QMessageBox.critical(self.parent(), "Base version", "Please select a base version")
return
base_version = current.data(0, QtCore.Qt.UserRole)
new_version_name, ok = QtWidgets.QInputDialog.getText(self, "Creating a new version", "Create a new version for this appliance.\nPlease share your experience on the GNS3 community if this version works.\n\nVersion name:", QtWidgets.QLineEdit.Normal, base_version.get("name"))
if ok:
new_version = {"name": new_version_name}
new_version["images"] = {}
for disk_type in base_version["images"]:
base_filename = base_version["images"][disk_type]["filename"]
filename, ok = QtWidgets.QInputDialog.getText(self, "Image", "Disk image filename for {}".format(disk_type), QtWidgets.QLineEdit.Normal, base_filename)
if not ok:
filename = base_filename
new_version["images"][disk_type] = {"filename": filename, "version": new_version_name}
try:
self._appliance.create_new_version(new_version)
except ApplianceError as e:
@@ -518,33 +485,9 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
QtWidgets.QMessageBox.warning(self.parent(), "Add appliance", "Can't access to the image file {}: {}.".format(path, str(e)))
return
image_upload_manger = ImageUploadManager(image, Controller.instance(), self._compute_id, self._imageUploadedCallback, LocalConfig.instance().directFileUpload())
image_upload_manger = ImageUploadManager(image, Controller.instance(), self.parent())
image_upload_manger.upload()
def _getQemuBinariesFromServerCallback(self, result, error=False, **kwargs):
"""
Callback for getQemuBinariesFromServer.
:param result: server response
:param error: indicates an error (boolean)
"""
if error:
QtWidgets.QMessageBox.critical(self, "Qemu binaries", "{}".format(result["message"]))
else:
self.uiQemuListComboBox.clear()
for qemu in result:
if qemu["version"]:
self.uiQemuListComboBox.addItem("{path} (v{version})".format(path=qemu["path"], version=qemu["version"]), qemu["path"])
else:
self.uiQemuListComboBox.addItem("{path}".format(path=qemu["path"]), qemu["path"])
if self.uiQemuListComboBox.count() == 1:
self.next()
else:
i = self.uiQemuListComboBox.findText(self._appliance["qemu"]["arch"], QtCore.Qt.MatchContains)
if i != -1:
self.uiQemuListComboBox.setCurrentIndex(i)
def _install(self, version):
"""
Install the appliance in GNS3
@@ -572,9 +515,6 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
return False
appliance_configuration["name"] = appliance_configuration["name"].strip()
if "qemu" in appliance_configuration:
appliance_configuration["qemu"]["path"] = self.uiQemuListComboBox.currentData()
new_template = ApplianceToTemplate().new_template(appliance_configuration, self._compute_id, self._symbols, parent=self)
TemplateManager.instance().createTemplate(Template(new_template), callback=self._templateCreatedCallback)
return False
@@ -613,34 +553,22 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
appliance_configuration = self._appliance.search_images_for_version(version)
except ApplianceError as e:
QtWidgets.QMessageBox.critical(self, "Appliance","Cannot install {} version {}: {}".format(name, version, e))
return
return False
for image in appliance_configuration["images"]:
if image["location"] == "local":
if not Controller.instance().isRemote() and self._compute_id == "local" and image["path"].startswith(ImageManager.instance().getDirectory()):
log.debug("{} is already on the local server".format(image["path"]))
return
image = Image(self._appliance.emulator(), image["path"], filename=image["filename"])
image_upload_manager = ImageUploadManager(image, Controller.instance(), self._compute_id, self._applianceImageUploadedCallback, LocalConfig.instance().directFileUpload())
image_upload_manager.upload()
self._image_uploading_count += 1
def _applianceImageUploadedCallback(self, result, error=False, context=None, **kwargs):
if context is None:
context = {}
image_path = context.get("image_path", "unknown")
if error:
log.error("Error while uploading image '{}': {}".format(image_path, result["message"]))
else:
log.info("Image '{}' has been successfully uploaded".format(image_path))
self._image_uploading_count -= 1
image_upload_manager = ImageUploadManager(image, Controller.instance(), self.parent())
if not image_upload_manager.upload():
return False
return True
def nextId(self):
if self.currentPage() == self.uiServerWizardPage:
if "docker" in self._appliance:
# skip Qemu binary selection and files pages if this is a Docker appliance
return super().nextId() + 2
elif "qemu" not in self._appliance:
# skip the Qemu binary selection page if not a Qemu appliance
return super().nextId() + 1
return super().nextId()
@@ -671,7 +599,7 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
if reply == QtWidgets.QMessageBox.No:
return False
self._uploadImages(appliance["name"], version["name"])
return self._uploadImages(appliance["name"], version["name"])
elif self.currentPage() == self.uiUsageWizardPage:
# validate the usage page
@@ -696,8 +624,6 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
QtWidgets.QMessageBox.critical(self, "Remote server", "There is no remote servers configured in your preferences")
return False
self._compute_id = self.uiRemoteServersComboBox.itemData(self.uiRemoteServersComboBox.currentIndex()).id()
elif hasattr(self, "uiVMRadioButton") and self.uiVMRadioButton.isChecked():
self._compute_id = "vm"
else:
if ComputeManager.instance().localPlatform():
if (ComputeManager.instance().localPlatform().startswith("darwin") or ComputeManager.instance().localPlatform().startswith("win")):
@@ -707,29 +633,8 @@ class ApplianceWizard(QtWidgets.QWizard, Ui_ApplianceWizard):
return False
self._compute_id = "local"
elif self.currentPage() == self.uiQemuWizardPage:
# validate the Qemu
if self._server_check is False:
QtWidgets.QMessageBox.critical(self, "Checking for KVM support", "Please wait for the server to reply...")
return False
if self.uiQemuListComboBox.currentIndex() == -1:
QtWidgets.QMessageBox.critical(self, "Qemu binary", "No compatible Qemu binary selected")
return False
return True
@qslot
def _vmToggledSlot(self, checked):
"""
Slot for when the VM radio button is toggled.
:param checked: either the button is checked or not
"""
if checked:
self.uiRemoteServersGroupBox.setEnabled(False)
self.uiRemoteServersGroupBox.hide()
@qslot
def _remoteServerToggledSlot(self, checked):
"""

View File

@@ -49,7 +49,6 @@ class ConfigurationDialog(QtWidgets.QDialog, Ui_configurationDialog):
self._settings = settings
self._configuration_page = configuration_page
@property
def settings(self):
return self._settings

View File

@@ -169,6 +169,9 @@ class CustomAdaptersConfigurationDialog(QtWidgets.QDialog, Ui_CustomAdaptersConf
adapter_number = item.data(0, QtCore.Qt.UserRole)
custom_adapter_settings["adapter_number"] = adapter_number
original_port_name = item.data(1, QtCore.Qt.UserRole)
if not port_name:
QtWidgets.QMessageBox.critical(self, "Port name", "Port name cannot be empty for adapter {}".format(adapter_number))
return False
if original_port_name != port_name:
custom_adapter_settings["port_name"] = port_name
if self._default_adapter_type and self._adapter_types:
@@ -180,13 +183,14 @@ class CustomAdaptersConfigurationDialog(QtWidgets.QDialog, Ui_CustomAdaptersConf
if mac_address and mac_address != ":::::":
if not re.search(r"""^([0-9a-fA-F]{2}[:]){5}[0-9a-fA-F]{2}$""", mac_address):
QtWidgets.QMessageBox.critical(self, "MAC address", "Invalid MAC address (format required: hh:hh:hh:hh:hh:hh)")
return
return False
default_mac_address = self._IntegerToMac(self._MacToInteger(self._base_mac_address) + adapter_number)
if mac_address != default_mac_address:
custom_adapter_settings["mac_address"] = mac_address
if len(custom_adapter_settings) > 1:
# only save if there is more than the adapter_number key
self._custom_adapters.append(custom_adapter_settings.copy())
return True
def done(self, result):
"""
@@ -196,5 +200,6 @@ class CustomAdaptersConfigurationDialog(QtWidgets.QDialog, Ui_CustomAdaptersConf
"""
if result:
self._updateCustomAdapters()
if not self._updateCustomAdapters():
return
super().done(result)

View File

@@ -15,11 +15,11 @@
# 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 sys
import psutil
import platform
import os
import stat
import sys
import struct
from gns3.qt import QtWidgets
@@ -92,19 +92,6 @@ class DoctorDialog(QtWidgets.QDialog, Ui_DoctorDialog):
return (1, "Experimental features are enabled. Turn them off by going to Preferences -> General -> Miscellaneous.")
return (0, None)
def checkAVGInstalled(self):
"""Checking if AVG software is not installed"""
if sys.platform.startswith("win32"):
for proc in psutil.process_iter():
try:
psinfo = proc.as_dict(["exe"])
if psinfo["exe"] and "AVG\\" in psinfo["exe"]:
return (2, "AVG has known issues with GNS3, even after you disable it. You must whitelist dynamips.exe in the AVG preferences.")
except psutil.NoSuchProcess:
pass
return (0, None)
def checkFreeRam(self):
"""Checking for amount of free virtual memory"""
@@ -186,39 +173,9 @@ class DoctorDialog(QtWidgets.QDialog, Ui_DoctorDialog):
pass
return (0, None)
def _checkWindowsService(self, service_name):
import pywintypes
import win32service
import win32serviceutil
try:
if win32serviceutil.QueryServiceStatus(service_name, None)[1] != win32service.SERVICE_RUNNING:
return False
except pywintypes.error as e:
if e.winerror == 1060:
return False
else:
raise
return True
def checkRPFServiceIsRunning(self):
"""Check if the RPF service is running (required to use Ethernet NIOs)"""
if not sys.platform.startswith("win"):
return (0, None)
import pywintypes
try:
if not self._checkWindowsService("npf") and not self._checkWindowsService("npcap"):
return (2, "The NPF or NPCAP service is not installed, please install Winpcap or Npcap and reboot")
except pywintypes.error as e:
return (2, "Could not check if the NPF or Npcap service is running: {}".format(e.strerror))
return (0, None)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main = QtWidgets.QMainWindow()
dialog = DoctorDialog(main, console=True)

View File

@@ -34,39 +34,15 @@ class EditComputeDialog(QtWidgets.QDialog, Ui_EditComputeDialog):
super().__init__(parent)
self.setupUi(self)
self.uiEnableAuthenticationCheckBox.toggled.connect(self._enableAuthenticationSlot)
self._compute = compute
if self._compute:
self.uiServerNameLineEdit.setText(self._compute.name())
self.uiServerHostLineEdit.setText(self._compute.host())
self.uiServerPortSpinBox.setValue(self._compute.port())
if self._compute.user():
self.uiEnableAuthenticationCheckBox.setChecked(True)
self.uiServerUserLineEdit.setText(self._compute.user())
else:
self.uiEnableAuthenticationCheckBox.setChecked(False)
self.uiWarningLabel.setVisible(False)
else:
self.uiEnableAuthenticationCheckBox.setChecked(False)
self.uiWarningLabel.setVisible(False)
self._enableAuthenticationSlot(self.uiEnableAuthenticationCheckBox.isChecked())
def _enableAuthenticationSlot(self, state):
"""
Slot to enable or not the authentication.
"""
if self.uiEnableAuthenticationCheckBox.isChecked():
self.uiServerUserLineEdit.setVisible(True)
self.uiServerPasswordLineEdit.setVisible(True)
self.uiServerUserLabel.setVisible(True)
self.uiServerPasswordLabel.setVisible(True)
else:
self.uiServerUserLineEdit.setVisible(False)
self.uiServerPasswordLineEdit.setVisible(False)
self.uiServerUserLabel.setVisible(False)
self.uiServerPasswordLabel.setVisible(False)
index = self.uiServerProtocolComboBox.findText(self._compute.protocol().upper())
self.uiServerProtocolComboBox.setCurrentIndex(index)
self.uiServerUserLineEdit.setText(self._compute.user())
def compute(self):
return self._compute
@@ -78,22 +54,22 @@ class EditComputeDialog(QtWidgets.QDialog, Ui_EditComputeDialog):
host = self.uiServerHostLineEdit.text().strip()
name = self.uiServerNameLineEdit.text().strip()
protocol = "http"
protocol = self.uiServerProtocolComboBox.currentText().lower()
port = self.uiServerPortSpinBox.value()
user = self.uiServerUserLineEdit.text().strip()
password = self.uiServerPasswordLineEdit.text().strip()
if not re.match(r"^[a-zA-Z0-9\.{}-]+$".format("\u0370-\u1CDF\u2C00-\u30FF\u4E00-\u9FBF"), host):
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid remote server hostname {}".format(host))
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid compute hostname {}".format(host))
return
if name == "gns3vm":
QtWidgets.QMessageBox.critical(self, "Remote compute", "{} is a reserved name".format(name))
return
if len(name) == 0:
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid remote server name {}".format(name))
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid compute name {}".format(name))
return
if port is None or port < 1:
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid remote server port {}".format(port))
QtWidgets.QMessageBox.critical(self, "Remote compute", "Invalid compute port {}".format(port))
return
if not self._compute:
@@ -102,12 +78,8 @@ class EditComputeDialog(QtWidgets.QDialog, Ui_EditComputeDialog):
self._compute.setProtocol(protocol)
self._compute.setHost(host)
self._compute.setPort(port)
if self.uiEnableAuthenticationCheckBox.isChecked():
self._compute.setUser(user)
self._compute.setPassword(password)
else:
self._compute.setUser(None)
self._compute.setPassword(None)
self._compute.setUser(user)
self._compute.setPassword(password)
super().accept()

View File

@@ -15,7 +15,9 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ..qt import QtWidgets, QtCore, qslot, qpartial
from gns3.utils import parse_version
from ..qt import QtGui, QtWidgets, QtCore, qslot, qpartial
from ..topology import Topology
from ..ui.edit_project_dialog_ui import Ui_EditProjectDialog
@@ -46,18 +48,38 @@ class EditProjectDialog(QtWidgets.QDialog, Ui_EditProjectDialog):
self.uiNewVarButton.clicked.connect(self.onAddNewVariable)
self.uiGlobalVariablesGrid.addWidget(self.uiNewVarButton, 0, 3, QtCore.Qt.AlignRight)
self._variables = self.setUpVariables()
self._readme_filename = "README.txt"
self.uiTabWidget.currentChanged.connect(self._previewMarkdownSlot)
self._loadReadme()
self._variables = self._project.variables()
if not self._variables:
self._variables = [{"name": "", "value": ""}]
self.updateGlobalVariables()
def setUpVariables(self):
new_variable = {"name": "", "value": ""}
variables = self._project.variables()
def _loadReadme(self):
if variables is not None:
variables.append(new_variable)
else:
variables = [new_variable]
return variables
self._project.get("/files/{}".format(self._readme_filename), self._loadedReadme, raw=True)
def _loadedReadme(self, result, error=False, context={}, **kwargs):
if not error:
content = result.decode("utf-8", errors="replace")
self.uiReadmeTextEdit.setPlainText(content)
def _previewMarkdownSlot(self, index):
# index 1 is preview tab
if index == 1:
# QTextDocument before Qt version 5.14 doesn't support Markdown
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.14.0") or parse_version(QtCore.PYQT_VERSION_STR) < parse_version("5.14.0"):
QtWidgets.QMessageBox.critical(self, "Markdown preview", "Markdown preview is only support with Qt version 5.14.0 or above")
return
# show Markdown preview
document = QtGui.QTextDocument()
self.uiReadmePreview.setDocument(document)
document.setMarkdown(self.uiReadmeTextEdit.toPlainText())
def updateGlobalVariables(self):
while True:
@@ -98,7 +120,7 @@ class EditProjectDialog(QtWidgets.QDialog, Ui_EditProjectDialog):
variable["value"] = text
def _cleanVariables(self):
return [v for v in self._variables if v.get("name", "").strip() != ""]
return [v for v in self._variables if v.get("name").strip() != ""]
def done(self, result):
"""
@@ -108,14 +130,27 @@ class EditProjectDialog(QtWidgets.QDialog, Ui_EditProjectDialog):
"""
if result:
self._project.setName(self.uiProjectNameLineEdit.text())
self._project.setAutoOpen(self.uiProjectAutoOpenCheckBox.isChecked())
self._project.setAutoClose(not self.uiProjectAutoCloseCheckBox.isChecked())
self._project.setAutoStart(self.uiProjectAutoStartCheckBox.isChecked())
self._project.setSceneHeight(self.uiSceneHeightSpinBox.value())
self._project.setSceneWidth(self.uiSceneWidthSpinBox.value())
self._project.setNodeGridSize(self.uiNodeGridSizeSpinBox.value())
self._project.setDrawingGridSize(self.uiDrawingGridSizeSpinBox.value())
self._project.setVariables(self._cleanVariables())
self._project.update()
node_grid_size = self.uiNodeGridSizeSpinBox.value()
drawing_grid_size = self.uiDrawingGridSizeSpinBox.value()
if node_grid_size % drawing_grid_size != 0:
QtWidgets.QMessageBox.critical(self, "Grid sizes", "Invalid grid sizes which will create overlapping lines")
else:
self._project.setNodeGridSize(node_grid_size)
self._project.setDrawingGridSize(drawing_grid_size)
self._project.setName(self.uiProjectNameLineEdit.text())
self._project.setAutoOpen(self.uiProjectAutoOpenCheckBox.isChecked())
self._project.setAutoClose(not self.uiProjectAutoCloseCheckBox.isChecked())
self._project.setAutoStart(self.uiProjectAutoStartCheckBox.isChecked())
self._project.setSceneHeight(self.uiSceneHeightSpinBox.value())
self._project.setSceneWidth(self.uiSceneWidthSpinBox.value())
self._project.setVariables(self._cleanVariables())
self._project.update()
content = self.uiReadmeTextEdit.toPlainText()
if content:
self._project.post("/files/{}".format(self._readme_filename), self._saveReadmeCallback, body=content)
super().done(result)
def _saveReadmeCallback(self, result, error=False, **kwargs):
if error:
QtWidgets.QMessageBox.critical(self, "Edit project", "Could not created readme file")

View File

@@ -64,9 +64,10 @@ class FileEditorDialog(QtWidgets.QDialog, Ui_FileEditorDialog):
def _refreshSlot(self):
self._target.get("/files/" + self._path, self._getCallback)
def _getCallback(self, result, error=False, raw_body=None, **kwargs):
def _getCallback(self, result, error=False, **kwargs):
if not error:
self.uiFileTextEdit.setText(raw_body.decode("utf-8", errors="ignore"))
self.uiFileTextEdit.setText(result)
elif result.get("status") == 404:
if self._default:
self.uiFileTextEdit.setText(self._default)

View File

@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 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 os
import pathlib
from gns3.http_client_error import HttpClientError, HttpClientCancelledRequestError
from ..qt import QtCore, QtWidgets, qslot, sip_is_deleted
from ..ui.image_dialog_ui import Ui_ImageDialog
from ..utils import human_size
from ..controller import Controller
import logging
log = logging.getLogger(__name__)
class ImageDialog(QtWidgets.QDialog, Ui_ImageDialog):
"""
Image management dialog.
"""
def __init__(self, parent):
"""
:param parent: parent widget.
"""
super().__init__(parent)
self.setupUi(self)
self.uiUploadImagePushButton.clicked.connect(self._uploadImageSlot)
self.uiDeleteImagePushButton.clicked.connect(self._deleteImageSlot)
self.uiRefreshImagesPushButton.clicked.connect(Controller.instance().refreshImageList)
Controller.instance().image_list_updated_signal.connect(self._updateImageListSlot)
self._updateImageListSlot()
Controller.instance().refreshImageList()
@qslot
def _uploadImageSlot(self, *args):
files, _ = QtWidgets.QFileDialog.getOpenFileNames(
self,
"Select one or more images to upload",
QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DownloadLocation),
"Images (*.bin *.image *.qcow2 *.vmdk);;All files (*.*)"
)
error_msgs = ""
for path in files:
log.debug("Uploading image '{}' to controller".format(path))
image_filename = os.path.basename(path)
install_appliances = self.uiInstallApplianceCheckBox.isChecked()
try:
Controller.instance().post(
f"/images/upload/{image_filename}",
params={"install_appliances": install_appliances},
body=pathlib.Path(path),
context={"image_path": path},
progress_text="Uploading {}".format(image_filename),
timeout=None,
wait=True
)
except HttpClientCancelledRequestError:
return
except HttpClientError as e:
error_msgs += f"{e}\n"
if error_msgs:
error_dialog = QtWidgets.QMessageBox(self)
error_dialog.setWindowModality(QtCore.Qt.ApplicationModal)
error_dialog.setWindowTitle("Image upload")
error_dialog.setText(f"Error while uploading images to the controller")
error_dialog.setDetailedText(error_msgs)
error_dialog.setIcon(QtWidgets.QMessageBox.Critical)
error_dialog.show()
Controller.instance().refreshImageList()
@qslot
def _deleteImageSlot(self, *args):
if len(self.uiImagesTreeWidget.selectedItems()) == 0:
QtWidgets.QMessageBox.critical(self, "Delete image", "No images selected")
return
reply = QtWidgets.QMessageBox.warning(
self,
"Delete image(s)",
"Delete the selected images?\nThis cannot be reverted.",
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.No:
return
images_to_delete = set()
for image in self.uiImagesTreeWidget.selectedItems():
if sip_is_deleted(image):
continue
image_filename = image.data(0, QtCore.Qt.UserRole)
images_to_delete.add(image_filename)
error_msgs = ""
for image_filename in images_to_delete:
try:
Controller.instance().delete(
f"/images/{image_filename}",
progress_text=f"Deleting {image_filename}",
timeout=None,
wait=True
)
except HttpClientCancelledRequestError:
return
except HttpClientError as e:
error_msgs += f"{e}\n"
if error_msgs:
error_dialog = QtWidgets.QMessageBox(self)
error_dialog.setWindowModality(QtCore.Qt.ApplicationModal)
error_dialog.setWindowTitle("Image deletion")
error_dialog.setText(f"Error while deleting images on the controller")
error_dialog.setDetailedText(error_msgs)
error_dialog.setIcon(QtWidgets.QMessageBox.Critical)
error_dialog.show()
Controller.instance().refreshImageList()
@qslot
def _updateImageListSlot(self, *args):
self.uiImagesTreeWidget.clear()
self.uiDeleteImagePushButton.setEnabled(False)
self.uiImagesTreeWidget.setUpdatesEnabled(False)
items = []
for image in Controller.instance().images():
item = QtWidgets.QTreeWidgetItem([image["filename"], image["image_type"], human_size(image["image_size"])])
item.setData(0, QtCore.Qt.UserRole, image["filename"])
items.append(item)
self.uiImagesTreeWidget.addTopLevelItems(items)
if len(Controller.instance().images()):
self.uiDeleteImagePushButton.setEnabled(True)
self.uiImagesTreeWidget.header().setResizeContentsPrecision(100) # How many rows are checked for the resize for performance reason
self.uiImagesTreeWidget.resizeColumnToContents(0)
self.uiImagesTreeWidget.resizeColumnToContents(1)
self.uiImagesTreeWidget.resizeColumnToContents(2)
self.uiImagesTreeWidget.sortItems(0, QtCore.Qt.AscendingOrder)
self.uiImagesTreeWidget.setUpdatesEnabled(True)
def keyPressEvent(self, e):
"""
Event handler in order to properly handle escape.
"""
if e.key() == QtCore.Qt.Key_Escape:
self.close()

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 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/>.
from ..qt import QtWidgets
from ..ui.login_dialog_ui import Ui_LoginDialog
import logging
log = logging.getLogger(__name__)
class LoginDialog(QtWidgets.QDialog, Ui_LoginDialog):
"""
Login dialog.
"""
def __init__(self, parent):
"""
:param parent: parent widget.
"""
super().__init__(parent)
self.setupUi(self)
self._parent = parent
self._username = None
self._password = None
def getUsername(self):
return self._username
def setUsername(self, username):
self.uiUsernameLineEdit.setText(username)
def getPassword(self):
return self._password
def done(self, result):
if result:
self._username = self.uiUsernameLineEdit.text()
self._password = self.uiPasswordLineEdit.text()
super().done(result)

View File

@@ -21,7 +21,7 @@ Dialog to load module and built-in preference pages.
from ..qt import QtCore, QtWidgets
from ..ui.preferences_dialog_ui import Ui_PreferencesDialog
from ..pages.server_preferences_page import ServerPreferencesPage
from ..pages.controller_preferences_page import ControllerPreferencesPage
from ..pages.general_preferences_page import GeneralPreferencesPage
from ..pages.packet_capture_preferences_page import PacketCapturePreferencesPage
from ..pages.gns3_vm_preferences_page import GNS3VMPreferencesPage
@@ -84,8 +84,8 @@ class PreferencesDialog(QtWidgets.QDialog, Ui_PreferencesDialog):
# load built-in preference pages
pages = [
GeneralPreferencesPage,
ServerPreferencesPage,
GNS3VMPreferencesPage,
ControllerPreferencesPage,
#GNS3VMPreferencesPage,
PacketCapturePreferencesPage,
]
@@ -131,6 +131,7 @@ class PreferencesDialog(QtWidgets.QDialog, Ui_PreferencesDialog):
QtWidgets.QLineEdit: "textChanged",
QtWidgets.QPlainTextEdit: "textChanged",
# QtWidgets.QTreeWidget: "itemChanged",
QtWidgets.QTreeWidget: "itemDoubleClicked",
QtWidgets.QComboBox: "currentIndexChanged",
QtWidgets.QSpinBox: "valueChanged",
QtWidgets.QAbstractButton: "pressed"

View File

@@ -53,7 +53,7 @@ class ProjectDialog(QtWidgets.QDialog, Ui_ProjectDialog):
if show_open_options:
self.uiOpenProjectPushButton.clicked.connect(self._openProjectActionSlot)
self.uiRecentProjectsPushButton.clicked.connect(self._showRecentProjectsSlot)
self._addRecentFilesMenu()
else:
self.uiOpenProjectGroupBox.hide()
self.uiProjectTabWidget.removeTab(1)
@@ -135,19 +135,28 @@ class ProjectDialog(QtWidgets.QDialog, Ui_ProjectDialog):
new_project_name)
name = name.strip()
if reply and len(name) > 0:
reset_mac_addresses = self.uiResetMacAddressesCheckBox.isChecked()
if Controller.instance().isRemote():
Controller.instance().post("/projects/{project_id}/duplicate".format(project_id=project_id),
self._duplicateCallback,
body={"name": name},
progressText="Duplicating project '{}'...".format(name),
timeout=None)
Controller.instance().post(
"/projects/{project_id}/duplicate".format(project_id=project_id),
self._duplicateCallback,
body={"name": name, "reset_mac_addresses": reset_mac_addresses},
progress_text="Duplicating project '{}'...".format(name),
timeout=None,
wait=True
)
else:
project_location = os.path.join(Topology.instance().projectsDirPath(), name)
Controller.instance().post("/projects/{project_id}/duplicate".format(project_id=project_id),
self._duplicateCallback,
body={"name": name, "path": project_location},
progressText="Duplicating project '{}'...".format(name),
timeout=None)
Controller.instance().post(
"/projects/{project_id}/duplicate".format(project_id=project_id),
self._duplicateCallback,
body={"name": name, "path": project_location, "reset_mac_addresses": reset_mac_addresses},
progress_text="Duplicating project '{}'...".format(name),
timeout=None,
wait=True
)
def _duplicateCallback(self, result, error=False, **kwargs):
if error:
@@ -228,20 +237,20 @@ class ProjectDialog(QtWidgets.QDialog, Ui_ProjectDialog):
self._main_window.openProjectActionSlot()
self.reject()
def _showRecentProjectsSlot(self):
def _addRecentFilesMenu(self):
"""
lot to show all the recent projects in a menu.
Add recent projects in a menu.
"""
menu = QtWidgets.QMenu()
menu.triggered.connect(self._menuTriggeredSlot)
menu = QtWidgets.QMenu(parent=self)
if Controller.instance().isRemote():
for action in self._main_window.recent_project_actions:
menu.addAction(action)
else:
for action in self._main_window.recent_file_actions:
menu.addAction(action)
menu.exec_(QtGui.QCursor.pos())
menu.triggered.connect(self._menuTriggeredSlot)
self.uiRecentProjectsPushButton.setMenu(menu)
def _overwriteProjectCallback(self, result, error=False, **kwargs):
if error:

View File

@@ -18,11 +18,11 @@
import sys
import datetime
from gns3.qt import QtCore, QtWidgets
from ..local_server import LocalServer
from ..utils.progress_dialog import ProgressDialog
from ..utils.export_project_worker import ExportProjectWorker
from ..ui.export_project_wizard_ui import Ui_ExportProjectWizard
from gns3.qt import QtCore, QtWidgets, QtGui
from gns3.utils import parse_version
from gns3.http_client_error import HttpClientError, HttpClientCancelledRequestError
from gns3.local_server import LocalServer
from gns3.ui.export_project_wizard_ui import Ui_ExportProjectWizard
import logging
log = logging.getLogger(__name__)
@@ -33,6 +33,8 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
Export project wizard.
"""
readme_signal = QtCore.pyqtSignal()
def __init__(self, project, parent):
super().__init__(parent)
@@ -49,14 +51,40 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
self.uiCompressionComboBox.addItem("Zip compression (deflate)", "zip")
self.uiCompressionComboBox.addItem("Bzip2 compression", "bzip2")
self.uiCompressionComboBox.addItem("Lzma compression", "lzma")
self.uiCompressionComboBox.addItem("Zstandard compression", "zstd")
self.uiCompressionComboBox.currentIndexChanged.connect(self._compressionChangedSlot)
# set zip compression by default
self.uiCompressionComboBox.setCurrentIndex(1)
# set zstd compression by default
self.uiCompressionComboBox.setCurrentIndex(4)
self.helpRequested.connect(self._showHelpSlot)
self.uiPathBrowserToolButton.clicked.connect(self._pathBrowserSlot)
readme_text = "Project: '{}' created on {}\nAuthor: John Doe <john.doe@example.com>\n\nNo project description was given".format(self._project.name(), datetime.date.today())
self.uiReadmeTextEdit.setPlainText(readme_text)
# QTextDocument before Qt version 5.14 doesn't support Markdown
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.14.0") or parse_version(QtCore.PYQT_VERSION_STR) < parse_version("5.14.0"):
self._use_markdown = False
else:
self._use_markdown = True
self._readme_filename = "README.txt"
self.uiTabWidget.currentChanged.connect(self._previewMarkdownSlot)
self._loadReadme()
def _loadReadme(self):
self._project.get("/files/{}".format(self._readme_filename), self._loadedReadme, raw=True)
def _loadedReadme(self, result, error=False, context={}, **kwargs):
if not error:
content = result.decode("utf-8", errors="replace")
self.uiReadmeTextEdit.setPlainText(content)
else:
if self._use_markdown:
readme_markdown = "# Project {}\n\nCreated on: {}\n\nAuthor: John Doe <john.doe@example.com>\n\n## Description\n\nNo project description was given".format(self._project.name(), datetime.date.today())
self.uiReadmeTextEdit.setPlainText(readme_markdown)
else:
readme_text = "Project: '{}' created on {}\nAuthor: John Doe <john.doe@example.com>\n\nNo project description was given".format(self._project.name(), datetime.date.today())
self.uiReadmeTextEdit.setPlainText(readme_text)
def _pathBrowserSlot(self):
@@ -64,14 +92,28 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
if len(directory) == 0:
directory = LocalServer.instance().localServerSettings()["projects_path"]
path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Export portable project", directory,
"GNS3 Portable Project (*.gns3project *.gns3p)",
"GNS3 Portable Project (*.gns3project *.gns3p)")
path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Export project", directory,
"GNS3 Project (*.gns3project *.gns3p)",
"GNS3 Project (*.gns3project *.gns3p)")
if path is None or len(path) == 0:
return
self.uiPathLineEdit.setText(path)
def _previewMarkdownSlot(self, index):
# index 1 is preview tab
if index == 1:
if self._use_markdown is False:
QtWidgets.QMessageBox.critical(self, "Markdown preview", "Markdown preview is only support with Qt version 5.14.0 or above")
return
# show Markdown preview
document = QtGui.QTextDocument()
self.uiReadmePreviewEdit.setDocument(document)
document.setMarkdown(self.uiReadmeTextEdit.toPlainText())
def _showHelpSlot(self):
include_image_help = """Including base images means additional images will not be requested to
@@ -99,15 +141,39 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
QtWidgets.QMessageBox.critical(self, "Export project", "Cannot export project to '{}': {}".format(path, e))
return False
self._path = path
elif self.currentPage() == self.uiProjectReadmeWizardPage:
text = self.uiReadmeTextEdit.toPlainText().strip()
if text:
self._project.post("/files/README.txt", self._saveReadmeCallback, body=text)
return True
def _saveReadmeCallback(self, result, error=False, **kwargs):
if error:
QtWidgets.QMessageBox.critical(self, "Export project", "Could not created readme file")
self.readme_signal.emit()
def waitForReadme(self, signal, timeout=10000):
# inspired from https://www.jdreaver.com/posts/2014-07-03-waiting-for-signals-pyside-pyqt.html
loop = QtCore.QEventLoop()
signal.connect(loop.quit)
if timeout is not None:
QtCore.QTimer.singleShot(timeout, loop.quit)
loop.exec_()
def _compressionChangedSlot(self, index):
"""
Set the default compression level.
"""
compression = self.uiCompressionComboBox.itemData(index)
self.uiCompressionLevelSpinBox.setEnabled(True)
if compression == "zip":
self.uiCompressionLevelSpinBox.setValue(6) # ZIP default compression level is 6
elif compression == "bzip2":
self.uiCompressionLevelSpinBox.setValue(9) # BZIP2 default compression level is 9
elif compression == "zstd":
self.uiCompressionLevelSpinBox.setValue(3) # ZSTD default compression level is 3
else:
# compression level is not supported
self.uiCompressionLevelSpinBox.setValue(0)
self.uiCompressionLevelSpinBox.setEnabled(False)
def done(self, result):
"""
@@ -115,6 +181,11 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
"""
if result:
content = self.uiReadmeTextEdit.toPlainText()
if content:
self._project.post("/files/{}".format(self._readme_filename), self._saveReadmeCallback, body=content)
if self.uiIncludeImagesCheckBox.isChecked():
include_images = "yes"
else:
@@ -123,9 +194,50 @@ class ExportProjectWizard(QtWidgets.QWizard, Ui_ExportProjectWizard):
include_snapshots = "yes"
else:
include_snapshots = "no"
if self.uiResetMacAddressesCheckBox.isChecked():
reset_mac_addresses = "yes"
else:
reset_mac_addresses = "no"
compression = self.uiCompressionComboBox.currentData()
export_worker = ExportProjectWorker(self._project, self._path, include_images, include_snapshots, compression)
progress_dialog = ProgressDialog(export_worker, "Exporting project", "Exporting portable project files...", "Cancel", parent=self, create_thread=False)
progress_dialog.show()
progress_dialog.exec_()
self.waitForReadme(self.readme_signal)
params = {
"include_images": include_images,
"include_snapshots": include_snapshots,
"reset_mac_addresses": reset_mac_addresses,
"compression": compression
}
try:
self._project.get(
"/export",
callback=None,
download_progress_callback=self._downloadFileProgress,
progress_text="Exporting project files...",
params=params,
timeout=None,
wait=True,
raw=True
)
except HttpClientCancelledRequestError:
pass
except HttpClientError as e:
QtWidgets.QMessageBox.critical(
self,
"Project export",
f"Could not export project: {e}"
)
super().done(result)
def _downloadFileProgress(self, content, **kwargs):
"""
Called for each part of the file
"""
try:
with open(self._path, 'ab') as f:
f.write(content)
except OSError as e:
log.error(f"Could not write project file: {e}")
return

View File

@@ -37,9 +37,7 @@ class ProjectWelcomeDialog(QtWidgets.QDialog, Ui_ProjectWelcomeDialog):
self.uiOkButton.clicked.connect(self._okButtonClickedSlot)
self.gridLayout.setAlignment(QtCore.Qt.AlignTop)
self.label.setOpenExternalLinks(True)
self._variables = self._getVariables(project)
self._loadReadme()
self._addMisingVariablesEdits()
@@ -50,10 +48,11 @@ class ProjectWelcomeDialog(QtWidgets.QDialog, Ui_ProjectWelcomeDialog):
return variables
def _addMisingVariablesEdits(self):
missing = [v for v in self._variables if v.get("value", "").strip() == ""]
#TODO: refactor this to use a QListWidget
missing = [v for v in self._variables if v.get("name") and v.get("value", "").strip() == ""]
for i, variable in enumerate(missing, start=0):
nameLabel = QtWidgets.QLabel()
nameLabel.setText(variable.get("name", ""))
nameLabel.setText(variable.get("name") + ":")
self.gridLayout.addWidget(nameLabel, i, 0)
valueEdit = QtWidgets.QLineEdit()
@@ -62,23 +61,23 @@ class ProjectWelcomeDialog(QtWidgets.QDialog, Ui_ProjectWelcomeDialog):
self.gridLayout.addWidget(valueEdit, i, 1)
def _loadReadme(self):
self._project.get("/files/README.txt", self._loadedReadme)
self._project.get("/files/README.txt", self._loadedReadme, raw=True)
def _loadedReadme(self, result, error=False, raw_body=None, context={}, **kwargs):
def _loadedReadme(self, result, error=False, context={}, **kwargs):
if not error:
self.label.setText(raw_body.decode("utf-8"))
self.label.setText(result.decode("utf-8"))
def onValueChange(self, variable, text):
variable["value"] = text
def _okButtonClickedSlot(self):
missing = [v for v in self._variables if v.get("value", "").strip() == ""]
missing = [v for v in self._variables if v.get("name") and v.get("value", "").strip() == ""]
if len(missing) > 0:
reply = QtWidgets.QMessageBox.warning(
self, 'Missing values',
'Are you sure you want to continue without providing missing values?',
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No)
reply = QtWidgets.QMessageBox.warning(self,
"Missing values",
"Are you sure you want to continue without providing missing values?",
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return

View File

@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
# Copyright (C) 2021 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
@@ -19,14 +19,12 @@ import sys
import os
import shutil
from gns3.qt import QtCore, QtWidgets, QtGui, QtNetwork, qslot
from gns3.qt import QtCore, QtWidgets, QtNetwork
from gns3.controller import Controller
from gns3.local_server import LocalServer
from gns3.utils.interfaces import interfaces
from ..settings import DEFAULT_LOCAL_SERVER_HOST
from ..settings import DEFAULT_CONTROLLER_HOST
from ..ui.setup_wizard_ui import Ui_SetupWizard
from ..version import __version__
import logging
@@ -45,39 +43,17 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
self.setupUi(self)
self.adjustSize()
self._gns3_vm_settings = {
"enable": True,
"headless": False,
"when_exit": "stop",
"engine": "vmware",
"vcpus": 1,
"ram": 2048,
"vmname": "GNS3 VM"
}
self.setWizardStyle(QtWidgets.QWizard.ModernStyle)
if sys.platform.startswith("darwin"):
# we want to see the cancel button on OSX
self.setOptions(QtWidgets.QWizard.NoDefaultButton)
self.uiLocalServerToolButton.clicked.connect(self._localServerBrowserSlot)
self.uiGNS3VMDownloadLinkUrlLabel.setText("")
self.uiRefreshPushButton.clicked.connect(self._refreshVMListSlot)
self.uiVmwareRadioButton.clicked.connect(self._listVMwareVMsSlot)
self.uiVirtualBoxRadioButton.clicked.connect(self._listVirtualBoxVMsSlot)
self.uiVMwareBannerButton.clicked.connect(self._VMwareBannerButtonClickedSlot)
settings = parent.settings()
self.uiShowCheckBox.setChecked(settings["hide_setup_wizard"])
# by default all radio buttons are unchecked
self.uiVmwareRadioButton.setAutoExclusive(False)
self.uiVirtualBoxRadioButton.setAutoExclusive(False)
self.uiVmwareRadioButton.setChecked(False)
self.uiVirtualBoxRadioButton.setChecked(False)
# Mandatory fields
self.uiLocalServerWizardPage.registerField("path*", self.uiLocalServerPathLineEdit)
self.uiLocalControllerWizardPage.registerField("path*", self.uiLocalServerPathLineEdit)
# load all available addresses
for address in QtNetwork.QNetworkInterface.allAddresses():
@@ -89,17 +65,16 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
continue
self.uiLocalServerHostComboBox.addItem(address_string, address_string)
if sys.platform.startswith("darwin"):
self.uiVMwareBannerButton.setIcon(QtGui.QIcon(":/images/vmware_fusion_banner.png"))
else:
self.uiVMwareBannerButton.setIcon(QtGui.QIcon(":/images/vmware_workstation_banner.png"))
self.uiLocalServerHostComboBox.addItem("localhost", "localhost") # local host
self.uiLocalServerHostComboBox.addItem("::", "::") # all IPv6 addresses
self.uiLocalServerHostComboBox.addItem("0.0.0.0", "0.0.0.0") # all IPv4 addresses
if sys.platform.startswith("linux"):
self.uiLocalRadioButton.setChecked(True)
self.uiLocalLabel.setText("Dependencies like Dynamips and Qemu must be manually installed")
Controller.instance().connected_signal.connect(self._refreshLocalServerStatusSlot)
Controller.instance().connection_failed_signal.connect(self._refreshLocalServerStatusSlot)
# only support local controller on Linux
self.uiLocalControllerRadioButton.setChecked(True)
else:
self.uiLocalControllerRadioButton.setEnabled(False)
self.uiRemoteControllerRadioButton.setChecked(True)
def _localServerBrowserSlot(self):
"""
@@ -116,43 +91,6 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
self.uiLocalServerPathLineEdit.setText(path)
def _VMwareBannerButtonClickedSlot(self):
if sys.platform.startswith("darwin"):
url = "http://send.onenetworkdirect.net/z/621395/CD225091/"
else:
url = "http://send.onenetworkdirect.net/z/616207/CD225091/"
QtGui.QDesktopServices.openUrl(QtCore.QUrl(url))
def _listVMwareVMsSlot(self):
"""
Slot to refresh the VMware VMs list.
"""
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VMware.Workstation.{version}.zip".format(version=__version__)
self.uiGNS3VMDownloadLinkUrlLabel.setText('The GNS3 VM can <a href="{download_url}">downloaded here</a>.<br>Import the VM in your virtualization software and hit refresh.'.format(download_url=download_url))
self.uiVirtualBoxRadioButton.setChecked(False)
from gns3.modules import VMware
settings = VMware.instance().settings()
if not os.path.exists(settings["vmrun_path"]):
QtWidgets.QMessageBox.critical(self, "VMware", "VMware vmrun tool could not be found, VMware or the VIX API (required for VMware player) is probably not installed. You can download it from https://www.vmware.com/support/developer/vix-api/. After installation you need to restart GNS3.")
return
self._refreshVMListSlot()
def _listVirtualBoxVMsSlot(self):
"""
Slot to refresh the VirtualBox VMs list.
"""
download_url = "https://github.com/GNS3/gns3-gui/releases/download/v{version}/GNS3.VM.VirtualBox.{version}.zip".format(version=__version__)
self.uiGNS3VMDownloadLinkUrlLabel.setText('If you don\'t have the GNS3 Virtual Machine you can <a href="{download_url}">download it here</a>.<br>And import the VM in the virtualization software and hit refresh.'.format(download_url=download_url))
self.uiVmwareRadioButton.setChecked(False)
from gns3.modules import VirtualBox
settings = VirtualBox.instance().settings()
if not os.path.exists(settings["vboxmanage_path"]):
QtWidgets.QMessageBox.critical(self, "VirtualBox", "VBoxManage could not be found, VirtualBox is probably not installed. After installation you need to restart GNS3.")
return
self._refreshVMListSlot()
def _setPreferencesPane(self, dialog, name):
"""
Finds the first child of the QTreeWidgetItem name.
@@ -168,13 +106,6 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
dialog.uiTreeWidget.setCurrentItem(child_pane)
return dialog.uiStackedWidget.currentWidget()
def _getSettingsCallback(self, result, error=False, **kwargs):
if error:
if "message" in result:
log.error("Error while get gettings: {}".format(result["message"]))
return
self._gns3_vm_settings = result
def initializePage(self, page_id):
"""
Initialize Wizard pages.
@@ -183,35 +114,16 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
"""
super().initializePage(page_id)
if self.page(page_id) == self.uiServerWizardPage:
if self.page(page_id) == self.uiControllerWizardPage:
Controller.instance().setDisplayError(False)
Controller.instance().get("/gns3vm", self._getSettingsCallback)
elif self.page(page_id) == self.uiVMWizardPage:
if self._GNS3VMSettings()["engine"] == "vmware":
self.uiVmwareRadioButton.setChecked(True)
self._listVMwareVMsSlot()
elif self._GNS3VMSettings()["engine"] == "virtualbox":
self.uiVirtualBoxRadioButton.setChecked(True)
self._listVirtualBoxVMsSlot()
self.uiCPUSpinBox.setValue(self._GNS3VMSettings()["vcpus"])
self.uiRAMSpinBox.setValue(self._GNS3VMSettings()["ram"])
elif self.page(page_id) == self.uiLocalServerWizardPage:
elif self.page(page_id) == self.uiLocalControllerWizardPage:
local_server_settings = LocalServer.instance().localServerSettings()
self.uiLocalServerPathLineEdit.setText(local_server_settings["path"])
index = self.uiLocalServerHostComboBox.findData(local_server_settings["host"])
if index != -1:
self.uiLocalServerHostComboBox.setCurrentIndex(index)
else:
if self.uiVMRadioButton.isChecked():
# Try to bind with the IP address allocated for VMnet1
for interface in interfaces():
if "vmnet1" in interface["name"].lower():
index = self.uiLocalServerHostComboBox.findText(interface["ip_address"])
break
else:
index = self.uiLocalServerHostComboBox.findText(DEFAULT_LOCAL_SERVER_HOST)
index = self.uiLocalServerHostComboBox.findText(DEFAULT_CONTROLLER_HOST)
if index != -1:
self.uiLocalServerHostComboBox.setCurrentIndex(index)
@@ -220,61 +132,28 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
elif self.page(page_id) == self.uiRemoteControllerWizardPage:
local_server_settings = LocalServer.instance().localServerSettings()
if local_server_settings["host"] is None:
self.uiRemoteMainServerHostLineEdit.setText(DEFAULT_LOCAL_SERVER_HOST)
self.uiRemoteMainServerAuthCheckBox.setChecked(False)
self.uiRemoteMainServerHostLineEdit.setText(DEFAULT_CONTROLLER_HOST)
self.uiRemoteMainServerUserLineEdit.setText("")
self.uiRemoteMainServerPasswordLineEdit.setText("")
else:
self.uiRemoteMainServerHostLineEdit.setText(local_server_settings["host"])
self.uiRemoteMainServerAuthCheckBox.setChecked(local_server_settings["auth"])
self.uiRemoteMainServerUserLineEdit.setText(local_server_settings["user"])
self.uiRemoteMainServerUserLineEdit.setText(local_server_settings["username"])
self.uiRemoteMainServerPasswordLineEdit.setText(local_server_settings["password"])
self.uiRemoteMainServerPortSpinBox.setValue(local_server_settings["port"])
elif self.page(page_id) == self.uiLocalServerStatusWizardPage:
self._refreshLocalServerStatusSlot()
elif self.page(page_id) == self.uiSummaryWizardPage:
self.uiSummaryTreeWidget.clear()
if self.uiLocalRadioButton.isChecked():
if self.uiLocalControllerRadioButton.isChecked():
local_server_settings = LocalServer.instance().localServerSettings()
self._addSummaryEntry("Server type:", "Local")
self._addSummaryEntry("Type:", "Local")
self._addSummaryEntry("Path:", local_server_settings["path"])
self._addSummaryEntry("Host:", local_server_settings["host"])
self._addSummaryEntry("Port:", str(local_server_settings["port"]))
elif self.uiRemoteControllerRadioButton.isChecked():
local_server_settings = LocalServer.instance().localServerSettings()
self._addSummaryEntry("Server type:", "Remote")
self._addSummaryEntry("Type:", "Remote")
self._addSummaryEntry("Host:", local_server_settings["host"])
self._addSummaryEntry("Port:", str(local_server_settings["port"]))
self._addSummaryEntry("User:", local_server_settings["user"])
else:
self._addSummaryEntry("Server type:", "GNS3 Virtual Machine")
self._addSummaryEntry("VM engine:", self._GNS3VMSettings()["engine"].capitalize())
self._addSummaryEntry("VM name:", self._GNS3VMSettings()["vmname"])
self._addSummaryEntry("VM vCPUs:", str(self._GNS3VMSettings()["vcpus"]))
self._addSummaryEntry("VM RAM:", str(self._GNS3VMSettings()["ram"]) + " MB")
@qslot
def _refreshLocalServerStatusSlot(self):
"""
Refresh the local server status page
"""
self.uiLocalServerTextEdit.clear()
if Controller.instance().connected():
self.uiLocalServerTextEdit.setText("Connection to the local GNS3 server has been successful!")
Controller.instance().get("/gns3vm", self._getSettingsCallback)
elif Controller.instance().connecting():
self.uiLocalServerTextEdit.setText("Please wait connection to the GNS3 server...")
else:
local_server_settings = LocalServer.instance().localServerSettings()
self.uiLocalServerTextEdit.setText("Connection to local server failed. Please try one of the following:\n\n- Make sure GNS3 is allowed to run by your firewall.\n- Go back and try to change the server host binding and/or the port\n- Check with a browser if you can connect to {protocol}://{host}:{port}.\n- Try to run {path} in a terminal to see if you have an error.".format(protocol=local_server_settings["protocol"], host=local_server_settings["host"], port=local_server_settings["port"], path=local_server_settings["path"]))
def _GNS3VMSettings(self):
return self._gns3_vm_settings
def _setGNS3VMSettings(self, settings):
Controller.instance().put("/gns3vm", self._saveSettingsCallback, settings, timeout=60 * 5)
self._addSummaryEntry("User:", local_server_settings["username"])
def _saveSettingsCallback(self, result, error=False, **kwargs):
if error:
@@ -296,112 +175,44 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
"""
Controller.instance().setDisplayError(True)
if self.currentPage() == self.uiVMWizardPage:
vmname = self.uiVMListComboBox.currentText()
if vmname:
# save the GNS3 VM settings
vm_settings = self._GNS3VMSettings()
vm_settings["enable"] = True
vm_settings["vmname"] = vmname
if self.currentPage() == self.uiLocalControllerWizardPage:
if self.uiVmwareRadioButton.isChecked():
vm_settings["engine"] = "vmware"
elif self.uiVirtualBoxRadioButton.isChecked():
vm_settings["engine"] = "virtualbox"
local_controller_settings = LocalServer.instance().localServerSettings()
local_controller_settings["auto_start"] = True
local_controller_settings["remote"] = False
local_controller_settings["path"] = self.uiLocalServerPathLineEdit.text().strip()
local_controller_settings["host"] = self.uiLocalServerHostComboBox.itemData(self.uiLocalServerHostComboBox.currentIndex())
local_controller_settings["port"] = self.uiLocalServerPortSpinBox.value()
# set the vCPU count and RAM
vpcus = self.uiCPUSpinBox.value()
ram = self.uiRAMSpinBox.value()
if ram < 1024:
QtWidgets.QMessageBox.warning(self, "GNS3 VM memory", "It is recommended to allocate a minimum of 1024 MB of memory to the GNS3 VM")
vm_settings["vcpus"] = vpcus
vm_settings["ram"] = ram
self._setGNS3VMSettings(vm_settings)
else:
if not self.uiVmwareRadioButton.isChecked() and not self.uiVirtualBoxRadioButton.isChecked():
QtWidgets.QMessageBox.warning(self, "GNS3 VM", "Please select VMware or VirtualBox")
else:
QtWidgets.QMessageBox.warning(self, "GNS3 VM", "Please select a VM. If no VM is listed, check if the GNS3 VM is correctly imported and press refresh.")
if not os.path.isfile(local_controller_settings["path"]):
QtWidgets.QMessageBox.critical(self, "Local server", "Could not find local server {}".format(local_controller_settings["path"]))
return False
elif self.currentPage() == self.uiLocalServerWizardPage:
local_server_settings = LocalServer.instance().localServerSettings()
local_server_settings["auto_start"] = True
local_server_settings["path"] = self.uiLocalServerPathLineEdit.text().strip()
local_server_settings["host"] = self.uiLocalServerHostComboBox.itemData(self.uiLocalServerHostComboBox.currentIndex())
local_server_settings["port"] = self.uiLocalServerPortSpinBox.value()
if not os.path.isfile(local_server_settings["path"]):
QtWidgets.QMessageBox.critical(self, "Local server", "Could not find local server {}".format(local_server_settings["path"]))
return False
if not os.access(local_server_settings["path"], os.X_OK):
QtWidgets.QMessageBox.critical(self, "Local server", "{} is not an executable".format(local_server_settings["path"]))
if not os.access(local_controller_settings["path"], os.X_OK):
QtWidgets.QMessageBox.critical(self, "Local server", "{} is not an executable".format(local_controller_settings["path"]))
return False
LocalServer.instance().updateLocalServerSettings(local_server_settings)
LocalServer.instance().updateLocalServerSettings(local_controller_settings)
# start and connect to the controller if required
if not LocalServer.instance().localServerAutoStartIfRequired():
return False
elif self.currentPage() == self.uiRemoteControllerWizardPage:
local_server_settings = LocalServer.instance().localServerSettings()
local_server_settings["auto_start"] = False
local_server_settings["host"] = self.uiRemoteMainServerHostLineEdit.text()
local_server_settings["port"] = self.uiRemoteMainServerPortSpinBox.value()
local_server_settings["protocol"] = "http"
local_server_settings["user"] = self.uiRemoteMainServerUserLineEdit.text()
local_server_settings["password"] = self.uiRemoteMainServerPasswordLineEdit.text()
local_server_settings["auth"] = self.uiRemoteMainServerAuthCheckBox.isChecked()
LocalServer.instance().updateLocalServerSettings(local_server_settings)
elif self.currentPage() == self.uiSummaryWizardPage:
if self.uiLocalRadioButton.isChecked():
# deactivate the GNS3 VM if using the local server
vm_settings = self._GNS3VMSettings()
vm_settings["enable"] = False
self._setGNS3VMSettings(vm_settings)
elif self.currentPage() == self.uiLocalServerStatusWizardPage:
if not Controller.instance().connected():
return False
remote_controller_settings = Controller.instance().settings()
remote_controller_settings["auto_start"] = False
remote_controller_settings["remote"] = True
remote_controller_settings["host"] = self.uiRemoteMainServerHostLineEdit.text()
remote_controller_settings["port"] = self.uiRemoteMainServerPortSpinBox.value()
remote_controller_settings["protocol"] = "http"
remote_controller_settings["username"] = self.uiRemoteMainServerUserLineEdit.text()
remote_controller_settings["password"] = self.uiRemoteMainServerPasswordLineEdit.text()
Controller.instance().setSettings(remote_controller_settings)
Controller.instance().connect()
return Controller.instance().connected()
return True
def _refreshVMListSlot(self):
"""
Refresh the list of VM available in VMware or VirtualBox.
"""
if self.uiVmwareRadioButton.isChecked():
Controller.instance().get("/gns3vm/engines/vmware/vms", self._getVMsFromServerCallback, progressText="Retrieving VMware VM list from server...")
elif self.uiVirtualBoxRadioButton.isChecked():
Controller.instance().get("/gns3vm/engines/virtualbox/vms", self._getVMsFromServerCallback, progressText="Retrieving VirtualBox VM list from server...")
def _getVMsFromServerCallback(self, result, error=False, **kwargs):
"""
Callback for getVMsFromServer.
:param progress_dialog: QProgressDialog instance
:param result: server response
:param error: indicates an error (boolean)
"""
if error:
QtWidgets.QMessageBox.critical(self, "VM List", "{}".format(result["message"]))
else:
self.uiVMListComboBox.clear()
for vm in result:
self.uiVMListComboBox.addItem(vm["vmname"])
index = self.uiVMListComboBox.findText(self._GNS3VMSettings()["vmname"])
if index != -1:
self.uiVMListComboBox.setCurrentIndex(index)
else:
index = self.uiVMListComboBox.findText("GNS3 VM")
if index != -1:
self.uiVMListComboBox.setCurrentIndex(index)
else:
QtWidgets.QMessageBox.critical(self, "GNS3 VM", "Could not find a VM named 'GNS3 VM', is it imported in VMware or VirtualBox?")
def done(self, result):
"""
This dialog is closed.
@@ -415,9 +226,7 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
settings["hide_setup_wizard"] = True
else:
local_server_settings = LocalServer.instance().localServerSettings()
if local_server_settings["host"] is None:
local_server_settings["host"] = DEFAULT_LOCAL_SERVER_HOST
LocalServer.instance().updateLocalServerSettings(local_server_settings)
LocalServer.instance().updateLocalServerSettings(local_server_settings)
settings["hide_setup_wizard"] = not self.uiShowCheckBox.isChecked()
self.parentWidget().setSettings(settings)
super().done(result)
@@ -428,20 +237,17 @@ class SetupWizard(QtWidgets.QWizard, Ui_SetupWizard):
"""
current_id = self.currentId()
if self.page(current_id) == self.uiLocalServerStatusWizardPage and not self.uiVMRadioButton.isChecked():
if self.page(current_id) == self.uiLocalControllerWizardPage and self.uiLocalControllerRadioButton.isChecked():
return self._pageId(self.uiSummaryWizardPage)
if self.page(current_id) == self.uiServerWizardPage and self.uiRemoteControllerRadioButton.isChecked():
if self.page(current_id) == self.uiControllerWizardPage and self.uiRemoteControllerRadioButton.isChecked():
return self._pageId(self.uiRemoteControllerWizardPage)
if self.page(current_id) == self.uiVMWizardPage:
return self._pageId(self.uiSummaryWizardPage)
return QtWidgets.QWizard.nextId(self)
def _pageId(self, page):
"""
Return id of the page
"""
for id in self.pageIds():
if self.page(id) == page:
return id

View File

@@ -0,0 +1,71 @@
# -*- coding: utf-8 -*-
#
# 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/>.
import os
from gns3.qt import QtCore, QtGui, QtWidgets
from gns3.ui.show_readme_dialog_ui import Ui_ShowReadmeDialog
from gns3.utils import parse_version
import logging
log = logging.getLogger(__name__)
class ShowReadmeDialog(QtWidgets.QDialog, Ui_ShowReadmeDialog):
def __init__(self, project, path, content=None, parent=None):
if parent is None:
from gns3.main_window import MainWindow
parent = MainWindow.instance()
super().__init__(parent)
self.setupUi(self)
self._project = project
self._path = path
self.setWindowTitle(project.name() + " " + os.path.basename(path))
self.uiRefreshButton.pressed.connect(self._refreshSlot)
# QTextDocument before Qt version 5.14 doesn't support Markdown
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.14.0") or parse_version(QtCore.PYQT_VERSION_STR) < parse_version("5.14.0"):
self._markdown = False
else:
self._markdown = True
self._document = QtGui.QTextDocument()
self.uiTextBrowser.setDocument(self._document)
if content:
if self._markdown:
self._document.setMarkdown(content)
else:
self._document.setPlainText(content)
else:
self._refreshSlot()
def _refreshSlot(self):
self._project.get("/files/" + self._path, self._getCallback, raw=True)
def _getCallback(self, result, error=False, **kwargs):
if not error:
content = result.decode("utf-8", errors="ignore")
if self._markdown:
self._document.setMarkdown(content)
else:
self._document.setPlainText(content)

View File

@@ -85,11 +85,14 @@ class SnapshotsDialog(QtWidgets.QDialog, Ui_SnapshotsDialog):
snapshot_name, ok = QtWidgets.QInputDialog.getText(self, "Snapshot", "Snapshot name:", QtWidgets.QLineEdit.Normal, "Unnamed")
if ok and snapshot_name and self._project:
Controller.instance().post("/projects/{}/snapshots".format(self._project.id()),
self._createSnapshotsCallback,
{"name": snapshot_name},
progressText="Creation of snapshot '{}' in progress...".format(snapshot_name),
timeout=None)
Controller.instance().post(
"/projects/{}/snapshots".format(self._project.id()),
self._createSnapshotsCallback,
{"name": snapshot_name},
progress_text="Creation of snapshot '{}' in progress...".format(snapshot_name),
timeout=None,
wait=True
)
def _createSnapshotsCallback(self, result, error=False, server=None, context={}, **kwargs):
if error:
@@ -139,8 +142,13 @@ class SnapshotsDialog(QtWidgets.QDialog, Ui_SnapshotsDialog):
if reply == QtWidgets.QMessageBox.Cancel:
return
Controller.instance().post("/projects/{}/snapshots/{}/restore".format(self._project.id(), snapshot_id),
self._restoreSnapshotsCallback, progressText="Restoring snapshot...", timeout=None)
Controller.instance().post(
"/projects/{}/snapshots/{}/restore".format(self._project.id(), snapshot_id),
self._restoreSnapshotsCallback,
progress_text="Restoring snapshot...",
timeout=None,
wait=True
)
def _restoreSnapshotsCallback(self, result, error=False, server=None, context={}, **kwargs):

View File

@@ -22,6 +22,7 @@ Style editor to edit Shape items.
from ..qt import QtCore, QtWidgets, QtGui
from ..ui.style_editor_dialog_ui import Ui_StyleEditorDialog
from ..items.shape_item import ShapeItem
from ..items.line_item import LineItem
class StyleEditorDialog(QtWidgets.QDialog, Ui_StyleEditorDialog):
@@ -48,7 +49,8 @@ class StyleEditorDialog(QtWidgets.QDialog, Ui_StyleEditorDialog):
self.uiBorderStyleComboBox.addItem("Dot", QtCore.Qt.DotLine)
self.uiBorderStyleComboBox.addItem("Dash Dot", QtCore.Qt.DashDotLine)
self.uiBorderStyleComboBox.addItem("Dash Dot Dot", QtCore.Qt.DashDotDotLine)
self.uiBorderStyleComboBox.addItem("No border", QtCore.Qt.NoPen)
if True not in list(map(lambda item: isinstance(item, LineItem), items)):
self.uiBorderStyleComboBox.addItem("No border", QtCore.Qt.NoPen)
# use the first item in the list as the model
first_item = items[0]
@@ -70,7 +72,7 @@ class StyleEditorDialog(QtWidgets.QDialog, Ui_StyleEditorDialog):
self._border_color.green(),
self._border_color.blue(),
self._border_color.alpha()))
self.uiRotationSpinBox.setValue(first_item.rotation())
self.uiRotationSpinBox.setValue(int(first_item.rotation()))
self.uiBorderWidthSpinBox.setValue(pen.width())
index = self.uiBorderStyleComboBox.findData(pen.style())
if index != -1:

View File

@@ -0,0 +1,115 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Pekka Helenius
# Copyright (C) 2014 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/>.
"""
Style editor to edit Link items.
"""
from ..qt import QtCore, QtWidgets, QtGui
from ..ui.style_editor_dialog_ui import Ui_StyleEditorDialog
class StyleEditorDialogLink(QtWidgets.QDialog, Ui_StyleEditorDialog):
"""
Style editor dialog.
:param parent: parent widget
:param link: selected link
"""
def __init__(self, link, parent):
super().__init__(parent)
self.setupUi(self)
self._link = link
self._link_style = {}
self.uiBorderColorPushButton.clicked.connect(self._setBorderColorSlot)
self.uiButtonBox.button(QtWidgets.QDialogButtonBox.Apply).clicked.connect(self._applyPreferencesSlot)
self.uiBorderStyleComboBox.addItem("Solid", QtCore.Qt.SolidLine)
self.uiBorderStyleComboBox.addItem("Dash", QtCore.Qt.DashLine)
self.uiBorderStyleComboBox.addItem("Dot", QtCore.Qt.DotLine)
self.uiBorderStyleComboBox.addItem("Dash Dot", QtCore.Qt.DashDotLine)
self.uiBorderStyleComboBox.addItem("Dash Dot Dot", QtCore.Qt.DashDotDotLine)
self.uiBorderStyleComboBox.addItem("Invisible", QtCore.Qt.NoPen)
self.uiColorLabel.hide()
self.uiColorPushButton.hide()
self._color = None
self.uiRotationLabel.hide()
self.uiRotationSpinBox.hide()
pen = link.pen()
self._border_color = pen.color()
self.uiBorderColorPushButton.setStyleSheet("background-color: rgba({}, {}, {}, {});".format(self._border_color.red(),
self._border_color.green(),
self._border_color.blue(),
self._border_color.alpha()))
self.uiBorderWidthSpinBox.setValue(pen.width())
index = self.uiBorderStyleComboBox.findData(pen.style())
if index != -1:
self.uiBorderStyleComboBox.setCurrentIndex(index)
self.adjustSize()
def _setBorderColorSlot(self):
"""
Slot to select the border color.
"""
color = QtWidgets.QColorDialog.getColor(self._border_color, self, "Select Color", QtWidgets.QColorDialog.ShowAlphaChannel)
if color.isValid():
self._border_color = color
self.uiBorderColorPushButton.setStyleSheet("background-color: rgba({}, {}, {}, {});".format(self._border_color.red(),
self._border_color.green(),
self._border_color.blue(),
self._border_color.alpha()))
def _applyPreferencesSlot(self):
"""
Applies the new style settings.
"""
border_style = QtCore.Qt.PenStyle(self.uiBorderStyleComboBox.itemData(self.uiBorderStyleComboBox.currentIndex()))
pen = QtGui.QPen(self._border_color, self.uiBorderWidthSpinBox.value(), border_style, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)
self._link.setPen(pen)
new_link_style = {}
new_link_style["color"] = self._border_color.name()
new_link_style["width"] = self.uiBorderWidthSpinBox.value()
new_link_style["type"] = border_style
# Store values
self._link.setLinkStyle(new_link_style)
def done(self, result):
"""
Called when the dialog is closed.
:param result: boolean (accepted or rejected)
"""
if result:
self._applyPreferencesSlot()
super().done(result)

View File

@@ -67,6 +67,7 @@ class SymbolSelectionDialog(QtWidgets.QDialog, Ui_SymbolSelectionDialog):
self._symbol_items = []
self._parents = {}
Controller.instance().clearStaticCache() # TODO: use etag to know when to refresh the cache
Controller.instance().get("/symbols", self._listSymbolsCallback)
def _listSymbolsCallback(self, result, error=False, **kwargs):
@@ -108,6 +109,9 @@ class SymbolSelectionDialog(QtWidgets.QDialog, Ui_SymbolSelectionDialog):
item.setIcon(0, icon)
Controller.instance().getStatic(symbol.url(), qpartial(render, item))
for parent in self._parents.values():
parent.sortChildren(0, QtCore.Qt.AscendingOrder)
self.adjustSize()
def _searchTextChangedSlot(self, text):
@@ -119,13 +123,13 @@ class SymbolSelectionDialog(QtWidgets.QDialog, Ui_SymbolSelectionDialog):
"""
text = self.uiSearchLineEdit.text()
for item in self._symbol_items:
if not item.data(0, QtCore.Qt.UserRole).builtin():
item.setHidden(True)
# if not item.data(0, QtCore.Qt.UserRole).builtin():
# item.setHidden(True)
# else:
if not text.strip() or text.strip().lower() in item.text(0).lower():
item.setHidden(False)
else:
if len(text.strip()) == 0 or text.strip().lower() in item.text(0).lower():
item.setHidden(False)
else:
item.setHidden(True)
item.setHidden(True)
def _customSymbolToggledSlot(self, checked):
"""
@@ -187,7 +191,14 @@ class SymbolSelectionDialog(QtWidgets.QDialog, Ui_SymbolSelectionDialog):
SymbolSelectionDialog._symbols_dir = os.path.dirname(path)
symbol_id = os.path.basename(path)
Controller.instance().post("/symbols/" + symbol_id + "/raw", qpartial(self._finishSymbolUpload, path), body=pathlib.Path(path), progressText="Uploading {}".format(symbol_id), timeout=None)
Controller.instance().post(
"/symbols/" + symbol_id + "/raw",
qpartial(self._finishSymbolUpload, path),
body=pathlib.Path(path),
progress_text="Uploading {}".format(symbol_id),
timeout=None,
wait=True
)
def _finishSymbolUpload(self, path, result, error=False, **kwargs):
if error:

View File

@@ -44,7 +44,7 @@ class TextEditorDialog(QtWidgets.QDialog, Ui_TextEditorDialog):
# use the first item in the list as the model
first_item = items[0]
self._setColor(first_item.defaultTextColor())
self.uiRotationSpinBox.setValue(first_item.rotation())
self.uiRotationSpinBox.setValue(int(first_item.rotation()))
self.uiPlainTextEdit.setPlainText(first_item.toPlainText())
self.uiPlainTextEdit.setFont(first_item.font())

View File

@@ -135,14 +135,17 @@ class VMWithImagesWizard(VMWizard):
if create_button:
create_button.show()
def loadImagesList(self, endpoint):
def loadImagesList(self, image_type):
"""
Fill the list box with available Images"
Fill the list box with available images
:param endpoint: server endpoint with the list of Images
:param image_type: image type (qemu, iou or ios)
"""
Controller.instance().getCompute(endpoint, self._compute_id, self._getImagesFromServerCallback)
params = None
if image_type:
params = {"image_type": image_type}
Controller.instance().get("/images", self._getImagesFromServerCallback, params=params)
def _getImagesFromServerCallback(self, result, error=False, **kwargs):
"""
@@ -179,7 +182,7 @@ class VMWithImagesWizard(VMWizard):
if self._widgetOnCurrentPage(combo_box):
combo_box.clear()
for vm in result:
combo_box.addItem(vm["path"], vm)
combo_box.addItem(vm["filename"], vm)
def _widgetOnCurrentPage(self, widget):
"""

View File

@@ -94,8 +94,6 @@ class GraphicsView(QtWidgets.QGraphicsView):
self._drawing_grid_size = 25
self._last_mouse_position = None
self._topology = Topology.instance()
self._background_warning_msgbox = QtWidgets.QErrorMessage(self)
self._background_warning_msgbox.setWindowTitle("Layer position")
# set the scene
scene = QtWidgets.QGraphicsScene(parent=self)
@@ -326,6 +324,8 @@ class GraphicsView(QtWidgets.QGraphicsView):
# connect the signals that let the graphics view knows about events such as
# a new link creation or deletion.
if self._topology.addLink(link):
source_node.addLink(link)
destination_node.addLink(link)
link.add_link_signal.connect(self.addLinkSlot)
link.delete_link_signal.connect(self.deleteLinkSlot)
@@ -392,7 +392,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
# link addition code
if not self._newlink:
source_item = item
source_port = source_item.connectToPort()
source_port = source_item.connectToPort(event.globalPos())
if not source_port:
return
@@ -409,7 +409,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
source_item = self._newlink.sourceItem()
source_port = self._newlink.sourcePort()
destination_item = item
destination_port = destination_item.connectToPort()
destination_port = destination_item.connectToPort(event.globalPos())
if not destination_port:
return
@@ -460,28 +460,18 @@ class GraphicsView(QtWidgets.QGraphicsView):
else:
item.setSelected(True)
elif is_not_link and is_not_logo and event.button() == QtCore.Qt.RightButton and not self._adding_link:
if item and not sip.isdeleted(item):
# Prevent right clicking on a selected item from de-selecting all other items
if not item.isSelected():
if not event.modifiers() & QtCore.Qt.ControlModifier:
for it in self.scene().items():
it.setSelected(False)
item.setSelected(True)
self._showDeviceContextualMenu(QtGui.QCursor.pos())
else:
self._showDeviceContextualMenu(QtGui.QCursor.pos())
# when more than one item is selected display the contextual menu even if mouse is not above an item
elif len(self.scene().selectedItems()) > 1:
self._showDeviceContextualMenu(QtGui.QCursor.pos())
pass #TODO: remove this without creating a bug...
elif is_not_link and self._adding_link and event.button() == QtCore.Qt.RightButton:
# send a escape key to the main window to cancel the link addition
key = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_Escape, QtCore.Qt.NoModifier)
QtWidgets.QApplication.sendEvent(self._main_window, key)
elif item and isinstance(item, NodeItem) and self._adding_link and event.button() == QtCore.Qt.LeftButton:
self._userNodeLinking(event, item)
#context_event = QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse, event.pos())
#QtWidgets.QApplication.sendEvent(self, context_event)
elif event.button() == QtCore.Qt.LeftButton and self._adding_note:
pos = self.mapToScene(event.pos())
note = self.createDrawingItem("text", pos.x(), pos.y(), 2)
note = self.createDrawingItem("text", int(pos.x()), int(pos.y()), 2)
pos_x = note.pos().x()
pos_y = note.pos().y() - (note.boundingRect().height() / 2)
note.setPos(pos_x, pos_y)
@@ -491,19 +481,19 @@ class GraphicsView(QtWidgets.QGraphicsView):
self._adding_note = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_rectangle:
pos = self.mapToScene(event.pos())
self.createDrawingItem("rect", pos.x(), pos.y(), 1)
self.createDrawingItem("rect", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawRectangleAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_rectangle = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_ellipse:
pos = self.mapToScene(event.pos())
self.createDrawingItem("ellipse", pos.x(), pos.y(), 1)
self.createDrawingItem("ellipse", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawEllipseAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_ellipse = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_line:
pos = self.mapToScene(event.pos())
self.createDrawingItem("line", pos.x(), pos.y(), 1)
self.createDrawingItem("line", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawLineAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_line = False
@@ -512,6 +502,46 @@ class GraphicsView(QtWidgets.QGraphicsView):
self.toggleUiDeviceMenu()
def contextMenuEvent(self, event):
"""
Handles all context menu events.
:param event: QContextMenuEvent instance
"""
is_not_link = True
is_not_logo = True
item = self.itemAt(event.pos())
if item and sip.isdeleted(item):
return
if item and (isinstance(item, LinkItem) or isinstance(item.parentItem(), LinkItem)):
is_not_link = False
if item and (isinstance(item, LogoItem) or isinstance(item.parentItem(), LogoItem)):
is_not_logo = False
else:
for it in self.scene().items():
if isinstance(it, LinkItem):
it.setHovered(False)
if is_not_link and is_not_logo and not self._adding_link:
if item and not sip.isdeleted(item):
# Prevent right clicking on a selected item from de-selecting all other items
if not item.isSelected():
if not event.modifiers() & QtCore.Qt.ControlModifier:
for it in self.scene().items():
it.setSelected(False)
item.setSelected(True)
self._showDeviceContextualMenu(event.globalPos())
# when more than one item is selected display the contextual menu even if mouse is not above an item
elif len(self.scene().selectedItems()) > 1:
self._showDeviceContextualMenu(event.globalPos())
#elif item and isinstance(item, NodeItem) and self._adding_link:
# self._userNodeLinking(event, item)
else:
super().contextMenuEvent(event)
def mouseReleaseEvent(self, event):
"""
Handles all mouse release events.
@@ -547,7 +577,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
delta = event.angleDelta()
if delta is not None and delta.x() == 0:
# CTRL is pressed then use the mouse wheel to zoom in or out.
self.scaleView(pow(2.0, delta.y() / 240.0))
self.scaleView(pow(2.0, (delta.y()/2) / 240.0))
self._topology.project().setZoom(round(self.transform().m11() * 100))
self._topology.project().update()
else:
@@ -627,7 +657,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
if not self._adding_link:
if isinstance(item, NodeItem) and item.node().initialized():
item.setSelected(True)
if item.node().status() == Node.stopped or item.node().isAlwaysOn():
if item.node().status() == Node.stopped or item.node().consoleType() == "none" or item.node().consoleType() is None:
self.configureSlot()
return
else:
@@ -691,8 +721,8 @@ class GraphicsView(QtWidgets.QGraphicsView):
integer, ok = QtWidgets.QInputDialog.getInt(self, "Nodes", "Number of nodes:", 2, 1, 100, 1)
if ok:
for node_number in range(integer):
x = event.pos().x() - (150 / 2) + (node_number % max_nodes_per_line) * offset
y = event.pos().y() - (70 / 2) + (node_number // max_nodes_per_line) * offset
x = event.pos().x() - (150 // 2) + (node_number % max_nodes_per_line) * offset
y = event.pos().y() - (70 // 2) + (node_number // max_nodes_per_line) * offset
if self.createNodeFromTemplateId(template_id, QtCore.QPoint(x, y)) is False:
event.ignore()
break
@@ -724,6 +754,11 @@ class GraphicsView(QtWidgets.QGraphicsView):
self.populateDeviceContextualMenu(menu)
menu.exec_(pos)
menu.clear()
# Make sure to deselect all items.
# This is to prevent a bug on Windows
# see https://github.com/GNS3/gns3-gui/issues/2986
for it in self.scene().items():
it.setSelected(False)
def populateDeviceContextualMenu(self, menu):
"""
@@ -785,6 +820,18 @@ class GraphicsView(QtWidgets.QGraphicsView):
console_edit_action.triggered.connect(self.customConsoleActionSlot)
menu.addAction(console_edit_action)
if True in list(map(lambda item: isinstance(item, NodeItem), items)):
isolate_action = QtWidgets.QAction("Isolate", menu)
isolate_action.setIcon(get_icon("link-pause.svg"))
isolate_action.triggered.connect(self.isolateActionSlot)
menu.addAction(isolate_action)
if True in list(map(lambda item: isinstance(item, NodeItem), items)):
unisolate_action = QtWidgets.QAction("Un-isolate", menu)
unisolate_action.setIcon(get_icon("link-start.svg"))
unisolate_action.triggered.connect(self.unisolateActionSlot)
menu.addAction(unisolate_action)
if True in list(map(lambda item: isinstance(item, NodeItem), items)):
# Action: Change hostname
change_hostname_action = QtWidgets.QAction("Change hostname", menu)
@@ -826,19 +873,19 @@ class GraphicsView(QtWidgets.QGraphicsView):
bring_to_front_action.triggered.connect(self.bringToFrontSlot)
menu.addAction(bring_to_front_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "configFiles"), items)):
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configFiles()), items)):
import_config_action = QtWidgets.QAction("Import config", menu)
import_config_action.setIcon(get_icon("import.svg"))
import_config_action.triggered.connect(self.importConfigActionSlot)
menu.addAction(import_config_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "configFiles"), items)):
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configFiles()), items)):
export_config_action = QtWidgets.QAction("Export config", menu)
export_config_action.setIcon(get_icon("export.svg"))
export_config_action.triggered.connect(self.exportConfigActionSlot)
menu.addAction(export_config_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "configFiles"), items)):
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configTextFiles()), items)):
export_config_action = QtWidgets.QAction("Edit config", menu)
export_config_action.setIcon(get_icon("edit.svg"))
export_config_action.triggered.connect(self.editConfigActionSlot)
@@ -964,6 +1011,26 @@ class GraphicsView(QtWidgets.QGraphicsView):
if isinstance(item, NodeItem) and hasattr(item.node(), "reload") and item.node().initialized():
item.node().reload()
def isolateActionSlot(self):
"""
Slot to receive events from the isolate action in the
contextual menu.
"""
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "isolate") and item.node().initialized():
item.node().isolate()
def unisolateActionSlot(self):
"""
Slot to receive events from the unisolate action in the
contextual menu.
"""
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "unisolate") and item.node().initialized():
item.node().unisolate()
def configureActionSlot(self):
"""
Slot to receive events from the configure action in the
@@ -988,10 +1055,9 @@ class GraphicsView(QtWidgets.QGraphicsView):
if isinstance(item, NodeItem) and item.node().initialized():
new_hostname, ok = QtWidgets.QInputDialog.getText(self, "Change hostname", "Hostname:", QtWidgets.QLineEdit.Normal, item.node().name())
if ok:
if hasattr(item.node(), "validateHostname"):
if not item.node().validateHostname(new_hostname):
QtWidgets.QMessageBox.critical(self, "Change hostname", "Invalid name detected for this node: {}".format(new_hostname))
continue
if not new_hostname.strip():
QtWidgets.QMessageBox.critical(self, "Change hostname", "Hostname cannot be blank")
continue
item.node().update({"name": new_hostname})
def changeSymbolActionSlot(self):
@@ -1024,7 +1090,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
break
if os.path.exists(node_dir):
log.debug("Open %s in file manager")
log.debug(f"Open {node_dir} in file manager")
if QtGui.QDesktopServices.openUrl(QtCore.QUrl.fromLocalFile(node_dir)) is False:
QtWidgets.QMessageBox.critical(self, "Show in file manager", "Failed to open {}".format(node_dir))
break
@@ -1095,11 +1161,21 @@ class GraphicsView(QtWidgets.QGraphicsView):
def consoleFromAllItems(self):
"""
Console from all scene items, except builtin devices.
Console from all scene items with console type different than "none"
"""
items = [item for item in self.scene().items()
if not (isinstance(item, NodeItem) and isinstance(item.node().module(), Builtin))]
if isinstance(item, NodeItem) and item.node().consoleType() != "none"]
nb_items = len(items)
if nb_items > 10:
proceed = QtWidgets.QMessageBox.question(self,
"Console to all nodes",
"You are about to open console windows to {} nodes. Are you sure?".format(nb_items),
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No)
if proceed == QtWidgets.QMessageBox.No:
return
self.consoleFromItems(items)
def consoleActionSlot(self):
@@ -1178,7 +1254,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
items = []
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "configFiles") and item.node().initialized():
if isinstance(item, NodeItem) and item.node().configFiles() and item.node().initialized():
items.append(item)
if not items:
@@ -1209,17 +1285,17 @@ class GraphicsView(QtWidgets.QGraphicsView):
items = []
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "configFiles") and item.node().initialized():
if isinstance(item, NodeItem) and item.node().configTextFiles() and item.node().initialized():
items.append(item)
if not items:
return
for item in items:
if len(item.node().configFiles()) == 1:
config_file = item.node().configFiles()[0]
if len(item.node().configTextFiles()) == 1:
config_file = item.node().configTextFiles()[0]
else:
config_file, ok = QtWidgets.QInputDialog.getItem(self, "Edit file", "File to edit?", item.node().configFiles(), 0, False)
config_file, ok = QtWidgets.QInputDialog.getItem(self, "Edit file", "File to edit?", item.node().configTextFiles(), 0, False)
if not ok:
continue
dialog = FileEditorDialog(item.node(), config_file, parent=self)
@@ -1234,7 +1310,7 @@ class GraphicsView(QtWidgets.QGraphicsView):
items = []
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "configFiles") and item.node().initialized():
if isinstance(item, NodeItem) and item.node().configFiles() and item.node().initialized():
items.append(item)
if not items:
@@ -1361,7 +1437,15 @@ class GraphicsView(QtWidgets.QGraphicsView):
type = "rect"
else:
type = "image"
self.createDrawingItem(type, item.pos().x() + 20, item.pos().y() + 20, item.zValue(), rotation=item.rotation(), svg=item.toSvg())
self.createDrawingItem(
type,
int(item.pos().x()) + 20,
int(item.pos().y()) + 20,
item.zValue(),
rotation=item.rotation(),
svg=item.toSvg()
)
elif isinstance(item, NodeItem):
item.node().duplicate(item.pos().x() + 20, item.pos().y() + 20, item.zValue())
@@ -1503,6 +1587,9 @@ class GraphicsView(QtWidgets.QGraphicsView):
QtWidgets.QMessageBox.critical(self, "Delete", "Cannot delete node '{}' because it is locked".format(node.name()))
return
selected_nodes.append(node)
if isinstance(item, DrawingItem) and item.locked():
QtWidgets.QMessageBox.critical(self, "Delete", "Cannot delete drawing because it is locked")
return
if selected_nodes:
if len(selected_nodes) > 1:
question = "Do you want to permanently delete these {} nodes?".format(len(selected_nodes))
@@ -1610,11 +1697,11 @@ class GraphicsView(QtWidgets.QGraphicsView):
x = left
while x < rect.right():
painter.drawLine(x, rect.top(), x, rect.bottom())
painter.drawLine(x, int(rect.top()), x, int(rect.bottom()))
x += grid
y = top
while y < rect.bottom():
painter.drawLine(rect.left(), y, rect.right(), y)
painter.drawLine(int(rect.left()), y, int(rect.right()), y)
y += grid
painter.restore()

File diff suppressed because it is too large Load Diff

58
gns3/http_client_error.py Normal file
View File

@@ -0,0 +1,58 @@
#!/usr/bin/env python
#
# Copyright (C) 2021 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 HttpClientError(Exception):
def __init__(self, message: str):
super().__init__()
self._message = message
def __repr__(self):
return self._message
def __str__(self):
return self._message
class HttpClientNotFoundError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)
class HttpClientCancelledRequestError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)
class HttpClientBadRequestError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)
class HttpClientUnauthorizedError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)
class HttpClientForbiddenError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)
class HttpClientTimeoutError(HttpClientError):
def __init__(self, message: str):
super().__init__(message)

View File

@@ -20,11 +20,10 @@ import copy
import pathlib
from gns3.qt import QtWidgets
from gns3.local_server_config import LocalServerConfig
from gns3.settings import LOCAL_SERVER_SETTINGS
from gns3.controller import Controller
from gns3.utils.file_copy_worker import FileCopyWorker
from gns3.utils.progress_dialog import ProgressDialog
from gns3.http_client_error import HttpClientError, HttpClientCancelledRequestError
from gns3.registry.image import Image
@@ -69,7 +68,7 @@ class ImageManager:
"""
if (server and server != "local") or Controller.instance().isRemote():
return self._uploadImageToRemoteServer(source_path, server, node_type)
return self._uploadImageToRemoteServer(source_path, node_type, parent)
else:
destination_directory = self.getDirectoryForType(node_type)
destination_path = os.path.join(destination_directory, os.path.basename(source_path))
@@ -115,27 +114,45 @@ class ImageManager:
source_path = destination_path
return source_path
def _uploadImageToRemoteServer(self, path, server, node_type):
def _uploadImageToRemoteServer(self, path, node_type, parent):
"""
Upload image to remote server
:param path: File path on computer
:param server: The server where the images should be located
:param node_type: Image node_type
:returns path: Final path
"""
if node_type == 'QEMU':
upload_endpoint = '/qemu/images'
image_type = 'qemu'
elif node_type == 'IOU':
upload_endpoint = '/iou/images'
image_type = 'iou'
elif node_type == 'DYNAMIPS':
upload_endpoint = '/dynamips/images'
image_type = 'ios'
else:
raise Exception('Invalid node type')
filename = self._getRelativeImagePath(path, node_type).replace("\\", "/")
Controller.instance().postCompute('{}/{}'.format(upload_endpoint, filename), server, None, body=pathlib.Path(path), progressText="Uploading {}".format(filename), timeout=None)
try:
Controller.instance().post(
f"/images/upload/{filename}",
callback=None,
params={"image_type": image_type},
body=pathlib.Path(path),
progress_text="Uploading {}".format(filename),
timeout=None,
wait=True
)
except HttpClientCancelledRequestError:
return
except HttpClientError as e:
QtWidgets.QMessageBox.critical(
parent,
"Image upload",
f"Could not upload image {filename}: {e}"
)
return filename
def _getRelativeImagePath(self, path, node_type):
@@ -164,7 +181,7 @@ class ImageManager:
:returns: path to the default images directory
"""
return copy.copy(LocalServerConfig.instance().loadSettings("Server", LOCAL_SERVER_SETTINGS)['images_path'])
return copy.copy(Controller.instance().settings()['images_path'])
def getDirectoryForType(self, node_type):
"""

View File

@@ -17,9 +17,11 @@
import os
import pathlib
import urllib.parse
from gns3.http_client import HTTPClient
from gns3.http_client_error import HttpClientError, HttpClientCancelledRequestError
from gns3.qt import QtWidgets
from gns3.registry.image import Image
from gns3.controller import Controller
import logging
log = logging.getLogger(__name__)
@@ -27,64 +29,42 @@ log = logging.getLogger(__name__)
class ImageUploadManager(object):
"""
Manager over the image upload. Encapsulates file uploads to computes or via controller.
Manager over the image upload
"""
def __init__(self, image, controller, compute_id, callback=None, directFileUpload=False):
self._image = image
self._compute_id = compute_id
self._callback = callback
self._directFileUpload = directFileUpload
self._controller = controller
def __init__(self, image: Image, controller: Controller, parent: QtWidgets.QWidget):
self._image = image
self._controller = controller
self._parent = parent
def upload(self) -> bool:
def upload(self):
if not os.path.exists(self._image.path):
log.error("Image '{}' could not be found".format(self._image.path))
return
if self._directFileUpload:
# first obtain endpoint and know when target request
self._controller.getEndpoint(self._getComputePath(), self._compute_id, self._onLoadEndpointCallback, showProgress=False)
else:
self._fileUploadToController()
return False
return self._fileUploadToController()
def _getComputePath(self):
return '/{emulator}/images/{filename}'.format(emulator=self._image.emulator, filename=self._image.filename)
def _fileUploadToController(self) -> bool:
def _onLoadEndpointCallback(self, result, error=False, **kwargs):
if error:
if "message" in result:
log.error("Error while getting endpoint: {}".format(result["message"]))
return
# we know where is the endpoint and we trying to post there a file
endpoint = result['endpoint']
self._fileUploadToCompute(endpoint)
def _checkIfSuccessfulCallback(self, result, error=False, **kwargs):
if error:
connection_error = kwargs.get('connection_error', False)
if connection_error:
log.debug("During direct file upload compute is not visible. Fallback to upload via controller.")
# there was an issue with connection, probably we don't have a direct access to compute
# we need to fallback to uploading files via controller
self._fileUploadToController()
else:
if "message" in result:
log.error("Error while direct file upload: {}".format(result["message"]))
return
self._callback(result, error, **kwargs)
def _fileUploadToCompute(self, endpoint):
log.debug("Uploading image '{}' to compute".format(self._image.path))
parse_results = urllib.parse.urlparse(endpoint)
network_manager = self._controller.getHttpClient().getNetworkManager()
client = HTTPClient.fromUrl(endpoint, network_manager=network_manager)
# We don't retry connection as in case of fail we try direct file upload
client.setMaxRetryConnection(0)
client.createHTTPQuery('POST', parse_results.path, self._checkIfSuccessfulCallback, body=pathlib.Path(self._image.path),
context={"image_path": self._image.path}, progressText="Uploading {}".format(self._image.filename), timeout=None, prefix="")
def _fileUploadToController(self):
log.debug("Uploading image '{}' to controller".format(self._image.path))
self._controller.postCompute(self._getComputePath(), self._compute_id, self._callback, body=pathlib.Path(self._image.path),
context={"image_path": self._image.path}, progressText="Uploading {}".format(self._image.filename), timeout=None)
try:
self._controller.post(
f"/images/upload/{self._image.filename}",
callback=None,
body=pathlib.Path(self._image.path),
context={"image_path": self._image.path},
progress_text="Uploading {}".format(self._image.filename),
timeout=None,
wait=True
)
except HttpClientCancelledRequestError:
return False
except HttpClientError as e:
QtWidgets.QMessageBox.critical(
self._parent,
"Image upload",
f"Could not upload image {self._image.filename}: {e}"
)
return False
return True

View File

@@ -27,7 +27,7 @@ log = logging.getLogger(__name__)
class DrawingItem:
# Map QT stroke to SVG style
QT_DASH_TO_SVG = {
QtCore.Qt.SolidLine: "",
QtCore.Qt.SolidLine: "none",
QtCore.Qt.NoPen: None,
QtCore.Qt.DashLine: "25, 25",
QtCore.Qt.DotLine: "5, 25",
@@ -92,7 +92,7 @@ class DrawingItem:
def updateDrawing(self):
if self._id and not self.deleting() and self._project:
self._project.put("/drawings/" + self._id, self.updateDrawingCallback, body=self.__json__(), showProgress=False)
self._project.put("/drawings/" + self._id, self.updateDrawingCallback, body=self.__json__(), show_progress=False)
@qslot
def updateDrawingCallback(self, result, error=False, **kwargs):
@@ -212,14 +212,13 @@ class DrawingItem:
self._project.delete("/drawings/" + self._id, None, body=self.__json__())
def itemChange(self, change, value):
if change == QtWidgets.QGraphicsItem.ItemPositionHasChanged and self.isActive() and self._main_window.uiSnapToGridAction.isChecked():
if change == QtWidgets.QGraphicsItem.ItemPositionChange and self.isActive() and self._main_window.uiSnapToGridAction.isChecked():
grid_size = self._graphics_view.drawingGridSize()
mid_x = self.boundingRect().width() / 2
tmp_x = (grid_size * round((self.x() + mid_x) / grid_size)) - mid_x
value.setX((grid_size * round((value.x() + mid_x) / grid_size)) - mid_x)
mid_y = self.boundingRect().height() / 2
tmp_y = (grid_size * round((self.y() + mid_y) / grid_size)) - mid_y
if tmp_x != self.x() and tmp_y != self.y():
self.setPos(tmp_x, tmp_y)
value.setY((grid_size * round((value.y()+mid_y)/grid_size)) - mid_y)
if change == QtWidgets.QGraphicsItem.ItemSelectedChange:
if not value:
@@ -247,7 +246,7 @@ class DrawingItem:
center = self.mapFromItem(self, brect.width() / 2.0, brect.height() / 2.0)
painter.setBrush(QtCore.Qt.red)
painter.setPen(QtCore.Qt.red)
painter.drawRect((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20)
painter.drawRect(QtCore.QRectF((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20))
painter.setPen(QtCore.Qt.black)
zval = str(int(self.zValue()))
painter.drawText(QtCore.QPointF(center.x() - 4, center.y() + 4), zval)

View File

@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Pekka Helenius
# Copyright (C) 2014 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
@@ -51,10 +52,16 @@ class EthernetLinkItem(LinkItem):
LinkItem.adjust(self)
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._pen_width + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtCore.Qt.black, self._pen_width, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
try:
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._link._link_style["width"] + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtGui.QColor(self._link._link_style["color"]), self._link._link_style["width"], self._link._link_style["type"], QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
except:
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._pen_width + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtGui.QColor("#000000"), self._pen_width, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
# draw a line between nodes
path = QtGui.QPainterPath(self.source)
@@ -152,7 +159,7 @@ class EthernetLinkItem(LinkItem):
else:
source_port_label.hide()
if self._settings["draw_link_status_points"]:
if self._settings["draw_link_status_points"] and self.pen().style() != QtCore.Qt.NoPen:
painter.drawPoint(point1)
if self._link.suspended() or self._destination_port.status() == Port.suspended:
@@ -195,7 +202,7 @@ class EthernetLinkItem(LinkItem):
else:
destination_port_label.hide()
if self._settings["draw_link_status_points"]:
if self._settings["draw_link_status_points"] and self.pen().style() != QtCore.Qt.NoPen:
painter.drawPoint(point2)
self._drawSymbol()

View File

@@ -165,7 +165,7 @@ class LabelItem(QtWidgets.QGraphicsTextItem):
center = self.mapFromItem(self, brect.width() / 2.0, brect.height() / 2.0)
painter.setBrush(QtCore.Qt.red)
painter.setPen(QtCore.Qt.red)
painter.drawRect((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20)
painter.drawRect(QtCore.QRectF((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20))
painter.setPen(QtCore.Qt.black)
zval = str(int(self.zValue()))
painter.drawText(QtCore.QPointF(center.x(), center.y()), zval)

View File

@@ -25,6 +25,7 @@ from ..qt import QtCore, QtGui, QtWidgets, QtSvg, qslot, sip_is_deleted
from ..packet_capture import PacketCapture
from ..dialogs.filter_dialog import FilterDialog
from ..dialogs.style_editor_dialog_link import StyleEditorDialogLink
from ..utils.get_icon import get_icon
@@ -137,12 +138,33 @@ class LinkItem(QtWidgets.QGraphicsPathItem):
def _suspendActionSlot(self, *args):
self._link.toggleSuspend()
@qslot
def _styleActionSlot(self, *args):
style_dialog = StyleEditorDialogLink(self, self._main_window)
style_dialog.show()
style_dialog.exec_()
def setLinkStyle(self, link_style):
self._link._link_style["color"] = link_style["color"]
self._link._link_style["width"] = link_style["width"]
self._link._link_style["type"] = link_style["type"]
# This refers to functions in link.py!
self._link.setLinkStyle(link_style)
self._link.update()
def delete(self):
"""
Delete this link
"""
self._link.deleteLink()
def reset(self):
"""
Reset this link
"""
self._link.resetLink()
def link(self):
"""
Returns the link attached to this link item.
@@ -266,6 +288,18 @@ class LinkItem(QtWidgets.QGraphicsPathItem):
resume_action.triggered.connect(self._suspendActionSlot)
menu.addAction(resume_action)
# reset
reset_action = QtWidgets.QAction("Reset", menu)
reset_action.setIcon(get_icon('reload.svg'))
reset_action.triggered.connect(self._resetActionSlot)
menu.addAction(reset_action)
# style
style_action = QtWidgets.QAction("Style", menu)
style_action.setIcon(get_icon("node_conception.svg"))
style_action.triggered.connect(self._styleActionSlot)
menu.addAction(style_action)
# delete
delete_action = QtWidgets.QAction("Delete", menu)
delete_action.setIcon(get_icon('delete.svg'))
@@ -280,23 +314,31 @@ class LinkItem(QtWidgets.QGraphicsPathItem):
:param: QGraphicsSceneMouseEvent instance
"""
if event.button() == QtCore.Qt.RightButton:
if self._adding_flag:
# send a escape key to the main window to cancel the link addition
from ..main_window import MainWindow
key = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_Escape, QtCore.Qt.NoModifier)
QtWidgets.QApplication.sendEvent(MainWindow.instance(), key)
return
if event.button() == QtCore.Qt.RightButton and self._adding_flag:
# send a escape key to the main window to cancel the link addition
from ..main_window import MainWindow
key = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_Escape, QtCore.Qt.NoModifier)
QtWidgets.QApplication.sendEvent(MainWindow.instance(), key)
return
else:
super().mousePressEvent(event)
if not sip_is_deleted(self):
# create the contextual menu
self.setAcceptHoverEvents(False)
menu = QtWidgets.QMenu()
self.populateLinkContextualMenu(menu)
menu.exec_(QtGui.QCursor.pos())
self.setAcceptHoverEvents(True)
self._hovered = False
self.adjust()
def contextMenuEvent(self, event):
"""
Handles all context menu events.
:param event: QContextMenuEvent instance
"""
if not sip_is_deleted(self):
# create the contextual menu
self.setAcceptHoverEvents(False)
menu = QtWidgets.QMenu()
self.populateLinkContextualMenu(menu)
menu.exec_(QtGui.QCursor.pos())
self.setAcceptHoverEvents(True)
self._hovered = False
self.adjust()
def keyPressEvent(self, event):
"""
@@ -310,6 +352,14 @@ class LinkItem(QtWidgets.QGraphicsPathItem):
self._deleteActionSlot()
return
def _resetActionSlot(self):
"""
Slot to receive events from the reset action in the
contextual menu.
"""
self.reset()
def _deleteActionSlot(self):
"""
Slot to receive events from the delete action in the

View File

@@ -388,7 +388,7 @@ class NodeItem(QtSvg.QGraphicsSvgItem):
else:
self._node_label.setPos(label_data["x"], label_data["y"])
def connectToPort(self, unavailable_ports=[]):
def connectToPort(self, pos, unavailable_ports=[]):
"""
Shows a contextual menu for the user to choose port or auto-select one.
@@ -436,7 +436,10 @@ class NodeItem(QtSvg.QGraphicsSvgItem):
menu.addAction(QtGui.QIcon(':/icons/led_green.svg'), port_object.name())
menu.triggered.connect(self.selectedPortSlot)
menu.exec_(QtGui.QCursor.pos())
# add some delay before showing the menu
# https://github.com/GNS3/gns3-gui/issues/3169
QtCore.QThread.msleep(100)
menu.exec_(pos)
return self._selected_port
def selectedPortSlot(self, action):
@@ -504,7 +507,7 @@ class NodeItem(QtSvg.QGraphicsSvgItem):
center = self.mapFromItem(self, brect.width() / 2.0, brect.height() / 2.0)
painter.setBrush(QtCore.Qt.red)
painter.setPen(QtCore.Qt.red)
painter.drawRect((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20)
painter.drawRect(QtCore.QRectF((brect.width() / 2.0) - 10, (brect.height() / 2.0) - 10, 20, 20))
painter.setPen(QtCore.Qt.black)
if self.show_layer:
text = str(int(self.zValue())) # Z value

View File

@@ -50,10 +50,16 @@ class SerialLinkItem(LinkItem):
LinkItem.adjust(self)
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._pen_width + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtCore.Qt.darkRed, self._pen_width, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
try:
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._link._link_style["width"] + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtGui.QColor(self._link._link_style["color"]), self._link._link_style["width"], self._link._link_style["type"], QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
except:
if self._hovered:
self.setPen(QtGui.QPen(QtCore.Qt.red, self._pen_width + 1, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
else:
self.setPen(QtGui.QPen(QtCore.Qt.darkRed, self._pen_width, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
# get source to destination angle
vector_angle = math.atan2(self.dy, self.dx)
@@ -141,7 +147,7 @@ class SerialLinkItem(LinkItem):
else:
source_port_label.hide()
if self._settings["draw_link_status_points"]:
if self._settings["draw_link_status_points"] and self.pen().style() != QtCore.Qt.NoPen:
painter.drawPoint(self.source_point)
# destination point color
@@ -173,7 +179,7 @@ class SerialLinkItem(LinkItem):
else:
destination_port_label.hide()
if self._settings["draw_link_status_points"]:
if self._settings["draw_link_status_points"] and self.pen().style() != QtCore.Qt.NoPen:
painter.drawPoint(self.destination_point)
self._drawSymbol()

View File

@@ -19,7 +19,6 @@
Manages and stores everything needed for a connection between 2 devices.
"""
import os
import re
from .qt import sip
import uuid
@@ -79,6 +78,7 @@ class Link(QtCore.QObject):
self._deleting = False
self._capture_file_path = None
self._capture_file = None
self._response_stream = None
self._capture_compute_id = None
self._initialized = False
self._filters = {}
@@ -90,9 +90,7 @@ class Link(QtCore.QObject):
self._creator = False
self._nodes = []
self._source_node.addLink(self)
self._destination_node.addLink(self)
self._link_style = {}
body = self._prepareParams()
if self._link_id:
@@ -119,19 +117,24 @@ class Link(QtCore.QObject):
else:
self._capture_file = QtCore.QFile(self._capture_file_path)
self._capture_file.open(QtCore.QFile.WriteOnly)
Controller.instance().get("/projects/{project_id}/links/{link_id}/pcap".format(project_id=self.project().id(), link_id=self._link_id),
None,
showProgress=False,
downloadProgressCallback=self._downloadPcapProgress,
ignoreErrors=True, # If something is wrong avoid disconnect us from server
timeout=None)
log.debug("Capturing packets to '{}'".format(self._capture_file_path))
self._response_stream = Controller.instance().get(
"/projects/{project_id}/links/{link_id}/capture/stream".format(project_id=self.project().id(), link_id=self._link_id),
callback=None,
show_progress=False,
download_progress_callback=self._downloadPcapProgress,
timeout=None
)
log.debug("Has successfully started capturing packets on link {} to '{}'".format(self._link_id, self._capture_file_path))
else:
self._response_stream = None
if "nodes" in result:
self._nodes = result["nodes"]
self._updateLabels()
if "filters" in result:
self._filters = result["filters"]
if "link_style" in result:
self._link_style = result["link_style"]
if "suspend" in result:
self._suspend = result["suspend"]
self.updated_link_signal.emit(self._id)
@@ -214,6 +217,7 @@ class Link(QtCore.QObject):
}
],
"filters": self._filters,
"link_style": self._link_style,
"suspend": self._suspend
}
if self._source_port.label():
@@ -345,20 +349,42 @@ class Link(QtCore.QObject):
# let the GUI know about this link has been deleted
self.delete_link_signal.emit(self._id)
def resetLink(self):
"""
Resets this link.
"""
log.debug("reset link from {} {} to {} {}".format(self._source_node.name(),
self._source_port.name(),
self._destination_node.name(),
self._destination_port.name()))
Controller.instance().post("/projects/{project_id}/links/{link_id}/reset".format(project_id=self.project().id(),
link_id=self._link_id),
self._linkResetCallback)
def _linkResetCallback(self, result, error=False, **kwargs):
"""
Called after the link is reset.
"""
if error:
log.error("Error while resetting link: {}".format(result["message"]))
return
def startCapture(self, data_link_type, capture_file_name):
data = {
"capture_file_name": capture_file_name,
"data_link_type": data_link_type
}
Controller.instance().post("/projects/{project_id}/links/{link_id}/start_capture".format(project_id=self.project().id(), link_id=self._link_id),
Controller.instance().post("/projects/{project_id}/links/{link_id}/capture/start".format(project_id=self.project().id(), link_id=self._link_id),
self._startCaptureCallback,
body=data)
def _startCaptureCallback(self, result, error=False, **kwargs):
if error:
log.error("Error while starting capture on link: {}".format(result["message"]))
log.error("Error while starting capture on link {}: {}".format(self._link_id, result["message"]))
return
#self._parseResponse(result)
def _downloadPcapProgress(self, content, server=None, context={}, **kwargs):
"""
@@ -382,15 +408,16 @@ class Link(QtCore.QObject):
# except OSError as e:
# log.error("Cannot remove file {}: {}".format(self._capture_file_path, e))
self._capture_file_path = None
Controller.instance().post("/projects/{project_id}/links/{link_id}/stop_capture".format(project_id=self.project().id(),
Controller.instance().post("/projects/{project_id}/links/{link_id}/capture/stop".format(project_id=self.project().id(),
link_id=self._link_id),
self._stopCaptureCallback)
def _stopCaptureCallback(self, result, error=False, **kwargs):
if error:
log.error("Error while stopping capture on link: {}".format(result["message"]))
log.error("Error while stopping capture on link {}: {}".format(self._link_id, result["message"]))
return
#self._parseResponse(result)
log.debug("Has successfully stopped capturing packets on link {}".format(self._link_id))
def get(self, path, callback, **kwargs):
"""
@@ -468,3 +495,9 @@ class Link(QtCore.QObject):
:params filters: List of filters
"""
self._filters = filters
def setLinkStyle(self, link_style):
"""
:params _link_style: Set link style attributes
"""
self._link_style = link_style

View File

@@ -26,8 +26,6 @@ import psutil
from .qt import QtCore, QtWidgets
from .version import __version__, __version_info__
from .utils import parse_version
from .local_server_config import LocalServerConfig
from .settings import LOCAL_SERVER_SETTINGS
import logging
log = logging.getLogger(__name__)
@@ -100,10 +98,10 @@ class LocalConfig(QtCore.QObject):
# migrate post version 2.2.0 configuration file
shutil.copyfile(old_config_path, self._config_file)
# reset the local server path and ubridge path
settings = LocalServerConfig.instance().loadSettings("Server", LOCAL_SERVER_SETTINGS)
settings["path"] = ""
settings["ubridge_path"] = ""
LocalServerConfig.instance().saveSettings("Server", settings)
# settings = LocalServerConfig.instance().loadSettings("Controller", CONTROLLER_SETTINGS)
# settings["path"] = ""
# settings["ubridge_path"] = ""
# LocalServerConfig.instance().saveSettings("Controller", settings)
else:
# create a new config
with open(self._config_file, "w", encoding="utf-8") as f:
@@ -416,20 +414,6 @@ class LocalConfig(QtCore.QObject):
settings["multi_profiles"] = value
self.saveSectionSettings("MainWindow", settings)
def directFileUpload(self):
"""
:returns: Boolean. True if direct_file_upload is enabled
"""
from gns3.settings import GENERAL_SETTINGS
return self.loadSectionSettings("MainWindow", GENERAL_SETTINGS)["direct_file_upload"]
def setDirectFileUpload(self, value):
from gns3.settings import GENERAL_SETTINGS
settings = self.loadSectionSettings("MainWindow", GENERAL_SETTINGS)
settings["direct_file_upload"] = value
self.saveSectionSettings("MainWindow", settings)
def showInterfaceLabelsOnNewProject(self):
"""
:returns: Boolean. True if show_interface_labels_on_new_project is enabled
@@ -488,7 +472,7 @@ class LocalConfig(QtCore.QObject):
if pid != my_pid:
try:
process = psutil.Process(pid=pid)
ps_name = process.name()
ps_name = process.name().lower()
except (OSError, psutil.NoSuchProcess, psutil.AccessDenied):
pass
else:

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
# Copyright (C) 2021 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
@@ -22,8 +22,6 @@ import stat
import shlex
import socket
import shutil
import random
import string
import struct
import psutil
import signal
@@ -31,13 +29,12 @@ import subprocess
from gns3.qt import QtWidgets, QtCore, qslot
from gns3.settings import LOCAL_SERVER_SETTINGS
from gns3.settings import DEFAULT_CONTROLLER_HOST
from gns3.local_config import LocalConfig
from gns3.local_server_config import LocalServerConfig
from gns3.http_client import HTTPClient
from gns3.utils.wait_for_connection_worker import WaitForConnectionWorker
from gns3.utils.progress_dialog import ProgressDialog
from gns3.utils.sudo import sudo
from gns3.http_client import HTTPClient
from gns3.controller import Controller
@@ -94,13 +91,6 @@ class LocalServer(QtCore.QObject):
self._settings = {}
self.localServerSettings()
self._port = self._settings.get("port", 3080)
if not self._settings.get("auto_start", True):
if self._settings.get("host") is None:
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
else:
self._http_client = None
self._stopping = False
self._timer = QtCore.QTimer()
self._timer.setInterval(5000)
@@ -122,27 +112,6 @@ class LocalServer(QtCore.QObject):
return MainWindow.instance()
return self._parent
def _checkWindowsService(self, service_name):
try:
import pywintypes
import win32service
import win32serviceutil
except ImportError as e:
log.error("Could not check if the {} service is running: {}".format(service_name, e))
return
try:
if win32serviceutil.QueryServiceStatus(service_name, None)[1] != win32service.SERVICE_RUNNING:
return False
except pywintypes.error as e:
if e.winerror == 1060: # service is not installed
return False
else:
log.error("Could not check if the {} service is running: {}".format(service_name, e.strerror))
return True
def _checkUbridgePermissions(self):
"""
Checks that uBridge can interact with network interfaces.
@@ -199,12 +168,6 @@ class LocalServer(QtCore.QObject):
return False
return True
def _passwordGenerate(self):
"""
Generate a random password
"""
return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(64))
def localServerSettings(self):
"""
Returns the local server settings.
@@ -212,14 +175,9 @@ class LocalServer(QtCore.QObject):
:returns: local server settings (dict)
"""
settings = LocalServerConfig.instance().loadSettings("Server", LOCAL_SERVER_SETTINGS)
settings = Controller.instance().settings()
self._settings = copy.copy(settings)
# user & password
if settings["auth"] is True and not settings["user"].strip():
settings["user"] = "admin"
settings["password"] = self._passwordGenerate()
# local GNS3 server path
local_server_path = shutil.which(settings["path"].strip())
if local_server_path is None:
@@ -246,13 +204,16 @@ class LocalServer(QtCore.QObject):
"""
Update the local server settings. Keep the key not in new_settings
"""
if "host" in new_settings and new_settings["host"] is None:
new_settings["host"] = DEFAULT_CONTROLLER_HOST
old_settings = copy.copy(self._settings)
if not self._settings:
self._settings = new_settings
else:
self._settings.update(new_settings)
self._port = self._settings["port"]
LocalServerConfig.instance().saveSettings("Server", self._settings)
Controller.instance().setSettings(self._settings)
# Settings have changed we need to restart the server
if old_settings != self._settings:
@@ -272,12 +233,6 @@ class LocalServer(QtCore.QObject):
else:
self.stopLocalServer(wait=True)
if self._settings.get("host") is None:
self._http_client = None
else:
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
def shouldLocalServerAutoStart(self):
"""
Returns either the local server
@@ -318,29 +273,24 @@ class LocalServer(QtCore.QObject):
Try to start the embedded gns3 server.
"""
if not self.shouldLocalServerAutoStart():
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
return
if self.isLocalServerRunning() and self._server_started_by_me:
local_server_already_running = self.isLocalServerRunning()
if local_server_already_running and self._server_started_by_me:
return True
# We check if two gui are not launched at the same time
# to avoid killing the server of the other GUI
if not LocalConfig.isMainGui():
log.info("Not the main GUI, will not auto start the server")
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
Controller.instance().connect()
return True
if self.isLocalServerRunning():
if local_server_already_running:
log.debug("A local server already running on this host")
# Try to kill the server. The server can be still running after
# if the server was started by hand
self._killAlreadyRunningServer()
if not self.isLocalServerRunning():
if not local_server_already_running:
if not self.initLocalServer():
QtWidgets.QMessageBox.critical(self.parent(), "Local server", "Could not start the local server process: {}".format(self._settings["path"]))
return False
@@ -351,15 +301,14 @@ class LocalServer(QtCore.QObject):
if self.parent():
worker = WaitForConnectionWorker(self._settings["host"], self._port)
progress_dialog = ProgressDialog(worker,
"Local server",
"Connecting to server {} on port {}...".format(self._settings["host"], self._port),
"Local controller",
"Starting local controller {} on port {}...".format(self._settings["host"], self._port),
"Cancel", busy=True, parent=self.parent())
progress_dialog.show()
if not progress_dialog.exec_():
return False
self._server_started_by_me = True
self._http_client = HTTPClient(self._settings)
Controller.instance().setHttpClient(self._http_client)
Controller.instance().connect()
return True
def initLocalServer(self):
@@ -368,15 +317,6 @@ class LocalServer(QtCore.QObject):
"""
self._checkUbridgePermissions()
if sys.platform.startswith("win"):
import pywintypes
try:
if not self._checkWindowsService("npf") and not self._checkWindowsService("npcap"):
log.warning("The NPF or NPCAP service is not installed, please install Winpcap or Npcap and reboot.")
except pywintypes.error as e:
log.warning("Could not check if the NPF or Npcap service is running: {}".format(e.strerror))
self._port = self._settings["port"]
# check the local server path
local_server_path = self.localServerPath()
@@ -469,7 +409,7 @@ class LocalServer(QtCore.QObject):
pass
except OSError as e:
log.warning("could not delete server log file {}: {}".format(logpath, e))
command += ' --log="{}" --pid="{}"'.format(logpath, self._pid_path())
command += ' --logfile="{}" --pid="{}"'.format(logpath, self._pid_path())
log.debug("Starting local server process with {}".format(command))
try:
@@ -518,19 +458,8 @@ class LocalServer(QtCore.QObject):
:returns: boolean
"""
status, json_data = HTTPClient(self._settings).getSynchronous("GET", "/version")
if status == 401: # Auth issue that need to be solved later
return True
elif json_data is None:
return False
elif status != 200:
return False
else:
version = json_data.get("version", None)
if version is None:
log.debug("Server is not a GNS3 server")
return False
return True
http_client = HTTPClient(self._settings)
return http_client.checkServerRunning()
def stopLocalServer(self, wait=False):
"""
@@ -541,13 +470,14 @@ class LocalServer(QtCore.QObject):
if self.localServerProcessIsRunning():
self._stopping = True
log.debug("Stopping local server (PID={})".format(self._local_server_process.pid))
log.debug("Stopping local controller (PID={})".format(self._local_server_process.pid))
# local server is running, let's stop it
if self._http_client:
self._http_client.shutdown()
http_client = Controller.instance().httpClient()
if http_client:
http_client.shutdown()
if wait:
worker = StopLocalServerWorker(self._local_server_process)
progress_dialog = ProgressDialog(worker, "Local server", "Waiting for the local server to stop...", None, busy=True, parent=self.parent())
progress_dialog = ProgressDialog(worker, "Local server", "Waiting for the local controller to stop...", None, busy=True, parent=self.parent())
progress_dialog.show()
progress_dialog.exec_()
if self._local_server_process.returncode is None:
@@ -570,8 +500,8 @@ class LocalServer(QtCore.QObject):
self._local_server_process.wait(timeout=60)
except subprocess.TimeoutExpired:
proceed = QtWidgets.QMessageBox.question(self.parent(),
"Local server",
"The Local server cannot be stopped, would you like to kill it?",
"Local controller",
"The local controller cannot be stopped, would you like to kill it?",
QtWidgets.QMessageBox.Yes,
QtWidgets.QMessageBox.No)

View File

@@ -1,163 +0,0 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 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 os
import sys
import configparser
import logging
log = logging.getLogger(__name__)
class LocalServerConfig:
"""
Local server configuration.
"""
def __init__(self, config_file=None):
appname = "GNS3"
self._config = configparser.RawConfigParser()
if config_file:
self._config_file = config_file
else:
if sys.platform.startswith("win"):
filename = "gns3_server.ini"
else:
filename = "gns3_server.conf"
from .local_config import LocalConfig
if sys.platform.startswith("win"):
self._config_file = os.path.join(LocalConfig.instance().configDirectory(), filename)
else:
self._config_file = os.path.join(LocalConfig.instance().configDirectory(), filename)
try:
# create the config file if it doesn't exist
open(self._config_file, "a").close()
except OSError as e:
log.error("Could not create the local server configuration {}: {}".format(self._config_file, e))
self.readConfig()
def setConfigFile(self, path):
"""
Change the location of the server config (use for test)
"""
self._config = configparser.RawConfigParser()
self._config_file = path
self.readConfig()
def readConfig(self):
"""
Read the configuration file.
"""
try:
self._config.read(self._config_file, encoding="utf-8")
except (OSError, configparser.Error, UnicodeEncodeError, UnicodeDecodeError) as e:
log.error("Could not read the local server configuration {}: {}".format(self._config_file, e))
def writeConfig(self):
"""
Write the configuration file.
"""
try:
log.debug("Write configuration file %s", self._config_file)
with open(self._config_file, "w", encoding="utf-8") as fp:
self._config.write(fp)
except (OSError, configparser.Error) as e:
log.error("Could not write the local server configuration {}: {}".format(self._config_file, e))
def loadSettings(self, section, default_settings):
"""
Get all the settings from a given section.
:param section: section name
:param default_settings: setting names and default values (dict)
:returns: settings (dict)
"""
if section not in self._config:
self._config[section] = {}
settings = {}
for name, default in default_settings.items():
if isinstance(default, bool):
settings[name] = self._config[section].getboolean(name, default)
elif isinstance(default, int):
settings[name] = self._config[section].getint(name, default)
elif isinstance(default, float):
settings[name] = self._config[section].getfloat(name, default)
else:
settings[name] = self._config[section].get(name, default)
if settings[name] == "None":
settings[name] = None
# sync with the config file
self.saveSettings(section, settings)
return settings
def saveSettings(self, section, settings):
"""
Save all the settings in a given section.
:param section: section name
:param settings: settings to save (dict)
"""
changed = False
if section not in self._config:
self._config[section] = {}
changed = True
for name, value in settings.items():
if name not in self._config[section] or self._config[section][name] != str(value):
self._config[section][name] = str(value)
changed = True
if changed:
self.writeConfig()
def deleteSetting(self, section, name):
"""
Delete a specific setting in a given section.
:param section: section name
:param name: setting name to delete
"""
if section in self._config and name in self._config[section]:
del self._config[section][name]
self.writeConfig()
@staticmethod
def instance():
"""
Singleton to return only on instance of LocalServerConfig.
:returns: instance of Config
"""
if not hasattr(LocalServerConfig, "_instance"):
LocalServerConfig._instance = LocalServerConfig()
return LocalServerConfig._instance

View File

@@ -118,6 +118,9 @@ def main():
# an extra argument starting with -psn_. We filter it
if sys.platform.startswith("darwin"):
sys.argv = [a for a in sys.argv if not a.startswith("-psn_")]
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.15.2"):
# Fixes issue on macOS Big Sur: https://github.com/GNS3/gns3-gui/issues/3037
os.environ["QT_MAC_WANTS_LAYER"] = "1"
parser = argparse.ArgumentParser()
parser.add_argument("project", help="load a GNS3 project (.gns3)", metavar="path", nargs="?")
@@ -143,7 +146,6 @@ def main():
frozen_dir,
os.path.normpath(os.path.join(frozen_dir, 'dynamips')),
os.path.normpath(os.path.join(frozen_dir, 'vpcs')),
os.path.normpath(os.path.join(frozen_dir, 'traceng'))
]
os.environ["PATH"] = os.pathsep.join(frozen_dirs) + os.pathsep + os.environ.get("PATH", "")
@@ -182,9 +184,9 @@ def main():
# catch exceptions to write them in a file
sys.excepthook = exceptionHook
# we only support Python 3 version >= 3.4
if sys.version_info < (3, 4):
raise SystemExit("Python 3.4 or higher is required")
# we only support Python 3 version >= 3.7
if sys.version_info < (3, 7):
raise SystemExit("Python 3.7 or higher is required")
if parse_version(QtCore.QT_VERSION_STR) < parse_version("5.5.0"):
raise SystemExit("Requirement is PyQt5 version 5.5.0 or higher, got version {}".format(QtCore.QT_VERSION_STR))
@@ -255,8 +257,7 @@ def main():
current_year = datetime.date.today().year
log.info("GNS3 GUI version {}".format(__version__))
log.info("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))
log.info("Application started with {}".format("".join(sys.argv)))
log.info("Application started with {}".format(" ".join(sys.argv)))
# update the exception file path to have it in the same directory as the settings file.
exception_file_path = os.path.join(LocalConfig.instance().configDirectory(), exception_file_path)

View File

@@ -39,6 +39,7 @@ from .dialogs.snapshots_dialog import SnapshotsDialog
from .dialogs.export_debug_dialog import ExportDebugDialog
from .dialogs.doctor_dialog import DoctorDialog
from .dialogs.edit_project_dialog import EditProjectDialog
from .dialogs.image_dialog import ImageDialog
from .dialogs.setup_wizard import SetupWizard
from .settings import GENERAL_SETTINGS
from .items.node_item import NodeItem
@@ -84,6 +85,42 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self._settings = {}
self.setupUi(self)
self.setUnifiedTitleAndToolBarOnMac(True)
# This widgets will be disable when you have no project loaded
self.disableWhenNoProjectWidgets = [
self.uiGraphicsView,
self.uiAnnotateMenu,
self.uiAnnotationToolBar,
self.uiControlToolBar,
self.uiControlMenu,
self.uiSaveProjectAsAction,
self.uiExportProjectAction,
self.uiScreenshotAction,
self.uiSnapshotAction,
self.uiEditProjectAction,
self.uiDeleteProjectAction,
self.uiImportExportConfigsAction,
self.uiLockAllAction,
self.uiShowReadmeAction
]
for widget in self.disableWhenNoProjectWidgets:
widget.setEnabled(False)
self.disableWhenControllerNotConnectedWidgets = [
self.uiNewProjectAction,
self.uiOpenProjectAction,
self.uiImportProjectAction,
self.uiNewTemplateAction,
self.uiImportProjectAction,
self.uiOpenApplianceAction,
self.uiWebUIAction,
self.uiNodesDockWidget
]
for widget in self.disableWhenControllerNotConnectedWidgets:
widget.setEnabled(False)
self._notif_dialog = NotifDialog(self)
# Setup logger
@@ -99,8 +136,6 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Controller.instance().setParent(self)
LocalServer.instance().setParent(self)
HTTPClient.setProgressCallback(Progress.instance(self))
self._first_file_load = True
self._open_project_path = None
self._loadSettings()
@@ -154,7 +189,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.uiFileMenu.insertActions(self.uiQuitAction, self.recent_file_actions)
self.recent_file_actions_separator = self.uiFileMenu.insertSeparator(self.uiQuitAction)
self.recent_file_actions_separator.setVisible(False)
self.updateRecentFileActions()
#self.updateRecentFileActions()
# add recent projects to the File menu
for i in range(0, self._maxrecent_files):
@@ -177,28 +212,6 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.setWindowTitle("[*] GNS3")
# This widgets will be disable when you have no project loaded
self.disableWhenNoProjectWidgets = [
self.uiGraphicsView,
self.uiAnnotateMenu,
self.uiAnnotationToolBar,
self.uiControlToolBar,
self.uiControlMenu,
self.uiSaveProjectAsAction,
self.uiExportProjectAction,
self.uiScreenshotAction,
self.uiSnapshotAction,
self.uiEditProjectAction,
self.uiDeleteProjectAction,
self.uiImportExportConfigsAction,
self.uiLockAllAction
]
# This widgets are not enabled if it's a remote controller (no access to the local file system)
self.disableWhenRemoteContollerWidgets = [
# self.uiImportExportConfigsAction
]
# load initial stuff once the event loop isn't busy
self.run_later(0, self.startupLoading)
@@ -212,6 +225,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.uiOpenProjectAction.triggered.connect(self.openProjectActionSlot)
self.uiOpenApplianceAction.triggered.connect(self.openApplianceActionSlot)
self.uiNewTemplateAction.triggered.connect(self._newTemplateActionSlot)
self.uiImageManagementAction.triggered.connect(self._imageManagementActionSlot)
self.uiSaveProjectAsAction.triggered.connect(self._saveProjectAsActionSlot)
self.uiExportProjectAction.triggered.connect(self._exportProjectActionSlot)
self.uiImportProjectAction.triggered.connect(self._importProjectActionSlot)
@@ -236,11 +250,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.uiResetPortLabelsAction.triggered.connect(self._resetPortLabelsActionSlot)
self.uiShowPortNamesAction.triggered.connect(self._showPortNamesActionSlot)
self.uiShowGridAction.triggered.connect(self._showGridActionSlot)
self.uiShowReadmeAction.triggered.connect(self._showReadmeActionSlot)
self.uiSnapToGridAction.triggered.connect(self._snapToGridActionSlot)
self.uiLockAllAction.triggered.connect(self._lockActionSlot)
self.uiResetDocksAction.triggered.connect(self._resetDocksSlot)
# tool menu connections
self.uiWebInterfaceAction.triggered.connect(self._openLightWebInterfaceActionSlot)
self.uiWebUIAction.triggered.connect(self._openWebInterfaceActionSlot)
# control menu connections
@@ -250,6 +265,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.uiReloadAllAction.triggered.connect(self._reloadAllActionSlot)
self.uiAuxConsoleAllAction.triggered.connect(self._auxConsoleAllActionSlot)
self.uiConsoleAllAction.triggered.connect(self._consoleAllActionSlot)
self.uiResetConsoleAllAction.triggered.connect(self._consoleResetAllActionSlot)
# device menu is contextual and is build on-the-fly
self.uiDeviceMenu.aboutToShow.connect(self._deviceMenuActionSlot)
@@ -260,6 +276,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.uiDrawRectangleAction.triggered.connect(self._drawRectangleActionSlot)
self.uiDrawEllipseAction.triggered.connect(self._drawEllipseActionSlot)
self.uiDrawLineAction.triggered.connect(self._drawLineActionSlot)
self.uiEditReadmeAction.triggered.connect(self._editReadmeActionSlot)
# help menu connections
self.uiOnlineHelpAction.triggered.connect(self._onlineHelpActionSlot)
@@ -322,14 +339,10 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
self.settings_updated_signal.emit()
def _openLightWebInterfaceActionSlot(self):
if Controller.instance().connected():
QtGui.QDesktopServices.openUrl(QtCore.QUrl(Controller.instance().httpClient().fullUrl()))
def _openWebInterfaceActionSlot(self):
if Controller.instance().connected():
base_url = Controller.instance().httpClient().fullUrl()
webui_url = "{}/static/web-ui/bundled".format(base_url)
webui_url = f"{base_url}/static/web-ui/bundled"
QtGui.QDesktopServices.openUrl(QtCore.QUrl(webui_url))
def _showGridActionSlot(self):
@@ -374,6 +387,16 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
item.updateNode()
item.update()
def _resetDocksSlot(self):
"""
Reset the dock widgets.
"""
self.uiTopologySummaryDockWidget.setFloating(False)
self.uiComputeSummaryDockWidget.setFloating(False)
self.uiConsoleDockWidget.setFloating(False)
self.uiNodesDockWidget.setFloating(False)
def analyticsClient(self):
"""
Return the analytics client
@@ -408,6 +431,15 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
dialog.show()
dialog.exec_()
def _imageManagementActionSlot(self):
"""
Called when user wants to manage images
"""
dialog = ImageDialog(self)
dialog.show()
dialog.exec_()
@qslot
def openApplianceActionSlot(self, *args):
"""
@@ -504,7 +536,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self._appliance_wizard.exec_()
elif path.endswith(".gns3"):
if Controller.instance().isRemote():
QtWidgets.QMessageBox.critical(self, "Open project", "Cannot open a .gns3 file on a remote server, please use a portable project (.gns3p) instead")
QtWidgets.QMessageBox.critical(self, "Open project", "Cannot open a .gns3 file on a remote server, please use a project (.gns3p) instead")
return
else:
Topology.instance().loadProject(path)
@@ -543,8 +575,9 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
"""
Refresh widgets that should be visible or not
"""
for widget in self.disableWhenRemoteContollerWidgets:
widget.setVisible(not Controller.instance().isRemote())
for widget in self.disableWhenControllerNotConnectedWidgets:
widget.setEnabled(Controller.instance().connected())
# No projects
if Topology.instance().project() is None:
@@ -813,6 +846,13 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
"""
Slot called when starting all the nodes.
"""
reply = QtWidgets.QMessageBox.question(self, "Confirm Start All", "Are you sure you want to start all devices?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return
project = Topology.instance().project()
if project is not None:
project.start_all_nodes()
@@ -822,6 +862,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Slot called when suspending all the nodes.
"""
reply = QtWidgets.QMessageBox.question(self, "Confirm Suspend All", "Are you sure you want to suspend all devices?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return
project = Topology.instance().project()
if project is not None:
project.suspend_all_nodes()
@@ -831,6 +877,12 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Slot called when stopping all the nodes.
"""
reply = QtWidgets.QMessageBox.question(self, "Confirm Stop All", "Are you sure you want to stop all devices?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return
project = Topology.instance().project()
if project is not None:
project.stop_all_nodes()
@@ -840,10 +892,25 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Slot called when reloading all the nodes.
"""
reply = QtWidgets.QMessageBox.question(self, "Confirm Reload All", "Are you sure you want to reload all devices?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.No:
return
project = Topology.instance().project()
if project is not None:
project.reload_all_nodes()
def _consoleResetAllActionSlot(self):
"""
Slot called when reset all console connections.
"""
project = Topology.instance().project()
if project is not None:
project.reset_console_all_nodes()
def _deviceMenuActionSlot(self):
"""
Slot to contextually show the device menu.
@@ -914,7 +981,7 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Slot to launch a browser pointing to the documentation page.
"""
QtGui.QDesktopServices.openUrl(QtCore.QUrl("https://gns3.com/support/docs"))
QtGui.QDesktopServices.openUrl(QtCore.QUrl("https://docs.gns3.com/"))
def _checkForUpdateActionSlot(self, silent=False):
"""
@@ -931,12 +998,9 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
Slot to open the setup wizard.
"""
with Progress.instance().context(min_duration=0):
setup_wizard = SetupWizard(self)
setup_wizard.show()
res = setup_wizard.exec_()
# start and connect to the local server if needed
LocalServer.instance().localServerAutoStartIfRequired()
setup_wizard = SetupWizard(self)
setup_wizard.show()
setup_wizard.exec_()
def _aboutQtActionSlot(self):
"""
@@ -1058,11 +1122,23 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
with Progress.instance().context(min_duration=0):
dialog = PreferencesDialog(self)
dialog.restoreGeometry(QtCore.QByteArray().fromBase64(self._settings["preferences_dialog_geometry"].encode()))
#dialog.restoreGeometry(QtCore.QByteArray().fromBase64(self._settings["preferences_dialog_geometry"].encode()))
dialog.show()
dialog.exec_()
self._settings["preferences_dialog_geometry"] = bytes(dialog.saveGeometry().toBase64()).decode()
self.setSettings(self._settings)
#self._settings["preferences_dialog_geometry"] = bytes(dialog.saveGeometry().toBase64()).decode()
#self.setSettings(self._settings)
def _editReadmeActionSlot(self):
"""
Slot to edit the README file
"""
Topology.instance().editReadme()
def _showReadmeActionSlot(self):
"""
Slot to show the README file
"""
Topology.instance().showReadme()
def resizeEvent(self, event):
self._notif_dialog.resize()
@@ -1182,8 +1258,9 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# restore debug level
if self._settings["debug_level"]:
print("Activating debugging (use command 'debug 0' to deactivate)")
root = logging.getLogger()
root.addHandler(logging.StreamHandler(sys.stdout))
root.setLevel(logging.DEBUG)
# restore the style
self._setStyle(self._settings.get("style"))
@@ -1198,13 +1275,11 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
if not self._settings["hide_setup_wizard"]:
self._setupWizardActionSlot()
else:
# start and connect to the local server if needed
LocalServer.instance().localServerAutoStartIfRequired()
if self._open_file_at_startup:
self.loadPath(self._open_file_at_startup)
self._open_file_at_startup = None
elif Topology.instance().project() is None:
self._newProjectActionSlot()
if Controller.instance().isRemote():
Controller.instance().connect()
else:
# start and connect to the local server if needed
LocalServer.instance().localServerAutoStartIfRequired()
if self._settings["check_for_update"]:
# automatic check for update every week (604800 seconds)
@@ -1357,9 +1432,17 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
self.recent_file_actions_separator.setVisible(False)
def _controllerConnectedSlot(self):
self.updateRecentFileActions()
self._refreshVisibleWidgets()
if self._settings["hide_setup_wizard"]:
if self._open_file_at_startup:
self.loadPath(self._open_file_at_startup)
self._open_file_at_startup = None
elif Topology.instance().project() is None:
self._newProjectActionSlot()
def run_later(self, counter, callback):
"""
Run a function after X milliseconds
@@ -1372,20 +1455,20 @@ class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def _exportProjectActionSlot(self):
"""
Slot called to export a portable project
Slot called to export a project
"""
Topology.instance().exportProject()
def _importProjectActionSlot(self):
"""
Slot called to import a portable project
Slot called to import a project
"""
directory = self._portable_project_dir
if not os.path.exists(directory):
directory = Topology.instance().projectsDirPath()
path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open portable project", directory,
path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open project", directory,
"All files (*.*);;GNS3 Portable Project (*.gns3project *.gns3p)",
"GNS3 Portable Project (*.gns3project *.gns3p)")
if path:

View File

@@ -19,12 +19,9 @@ from gns3.modules.builtin import Builtin
from gns3.modules.dynamips import Dynamips
from gns3.modules.iou import IOU
from gns3.modules.vpcs import VPCS
from gns3.modules.traceng import TraceNG
from gns3.modules.virtualbox import VirtualBox
from gns3.modules.qemu import Qemu
from gns3.modules.vmware import VMware
from gns3.modules.docker import Docker
#MODULES = [Builtin, VPCS, Dynamips, IOU, Qemu, VirtualBox, VMware, Docker, TraceNG]
#FIXME: deactivate TraceNG module
MODULES = [Builtin, VPCS, Dynamips, IOU, Qemu, VirtualBox, VMware, Docker]

View File

@@ -19,9 +19,7 @@
Built-in module implementation.
"""
from gns3.qt import QtWidgets
from gns3.local_config import LocalConfig
from gns3.local_server_config import LocalServerConfig
from ..module import Module
from .cloud import Cloud
@@ -53,14 +51,15 @@ class Builtin(Module):
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
server_settings = {}
config = LocalServerConfig.instance()
if self._settings["default_nat_interface"]:
# save some settings to the local server config file
server_settings["default_nat_interface"] = self._settings["default_nat_interface"]
config.saveSettings(self.__class__.__name__, server_settings)
else:
config.deleteSetting(self.__class__.__name__, "default_nat_interface")
# FIXME: handle server side config
# server_settings = {}
# config = LocalServerConfig.instance()
# if self._settings["default_nat_interface"]:
# # save some settings to the local server config file
# server_settings["default_nat_interface"] = self._settings["default_nat_interface"]
# config.saveSettings(self.__class__.__name__, server_settings)
# else:
# config.deleteSetting(self.__class__.__name__, "default_nat_interface")
def _loadSettings(self):
"""

View File

@@ -42,6 +42,7 @@ class Cloud(Node):
self._always_on = True
self._interfaces = {}
self._cloud_settings = {"ports_mapping": [],
"usage": "",
"remote_console_host": CLOUD_SETTINGS["remote_console_host"],
"remote_console_port": CLOUD_SETTINGS["remote_console_port"],
"remote_console_type": CLOUD_SETTINGS["remote_console_type"],
@@ -139,7 +140,8 @@ class Cloud(Node):
port_info += " Port {name} {description}\n".format(name=port.name(),
description=port.description())
return info + port_info
usage = "\n" + self._settings.get("usage")
return info + port_info + usage
def configPage(self):
"""

View File

@@ -48,7 +48,7 @@ class CloudWizard(VMWizard, Ui_CloudNodeWizard):
"""
settings = {"name": self.uiNameLineEdit.text(),
"symbol": ":/symbols/cloud.svg",
"symbol": "cloud",
"compute_id": self._compute_id}
return settings

View File

@@ -54,7 +54,7 @@ class EthernetHubWizard(VMWizard, Ui_EthernetHubWizard):
"name": "Ethernet{}".format(port_number)})
settings = {"name": self.uiNameLineEdit.text(),
"symbol": ":/symbols/hub.svg",
"symbol": "hub",
"category": Node.switches,
"compute_id": self._compute_id,
"ports_mapping": ports}

View File

@@ -54,10 +54,10 @@ class EthernetSwitchWizard(VMWizard, Ui_EthernetSwitchWizard):
"name": "Ethernet{}".format(port_number),
"type": "access",
"vlan": 1,
"ethertype": ""})
"ethertype": "0x8100"})
settings = {"name": self.uiNameLineEdit.text(),
"symbol": ":/symbols/ethernet_switch.svg",
"symbol": "ethernet_switch",
"category": Node.switches,
"compute_id": self._compute_id,
"ports_mapping": ports}

View File

@@ -473,9 +473,13 @@ class CloudConfigurationPage(QtWidgets.QWidget, Ui_cloudConfigPageWidget):
if index != -1:
self.uiCategoryComboBox.setCurrentIndex(index)
Controller.instance().getCompute("/network/interfaces", settings["compute_id"],
self._getInterfacesFromServerCallback,
progressText="Retrieving network interfaces...")
Controller.instance().getCompute(
"/network/interfaces",
settings["compute_id"],
self._getInterfacesFromServerCallback,
progress_text="Retrieving network interfaces...",
wait=True
)
else:
self.uiDefaultNameFormatLabel.hide()
@@ -490,6 +494,7 @@ class CloudConfigurationPage(QtWidgets.QWidget, Ui_cloudConfigPageWidget):
self._interfaces = self._node.interfaces()
self._loadNetworkInterfaces(self._interfaces)
self.uiUsageTextEdit.setPlainText(settings["usage"])
# load the current ports
self._ports = []
self.uiEthernetListWidget.clear()
@@ -560,4 +565,6 @@ class CloudConfigurationPage(QtWidgets.QWidget, Ui_cloudConfigPageWidget):
settings["ports_mapping"] = self._ports
else:
settings["ports_mapping"] = self._ports
settings["usage"] = self.uiUsageTextEdit.toPlainText()
return settings

View File

@@ -52,6 +52,7 @@ class CloudPreferencesPage(QtWidgets.QWidget, Ui_CloudPreferencesPageWidget):
self.uiEditCloudNodePushButton.clicked.connect(self._editCloudNodeSlot)
self.uiDeleteCloudNodePushButton.clicked.connect(self._deleteCloudNodeSlot)
self.uiCloudNodesTreeWidget.itemSelectionChanged.connect(self._cloudNodeChangedSlot)
self.uiCloudNodesTreeWidget.itemDoubleClicked.connect(self._editCloudNodeSlot)
def _createSectionItem(self, name):
"""
@@ -86,7 +87,11 @@ class CloudPreferencesPage(QtWidgets.QWidget, Ui_CloudPreferencesPageWidget):
QtWidgets.QTreeWidgetItem(section_item, ["Console type:", cloud_node["remote_console_type"]])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", cloud_node["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(cloud_node["compute_id"]).name()])
compute_id = cloud_node.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass

View File

@@ -53,6 +53,8 @@ class EthernetHubPreferencesPage(QtWidgets.QWidget, Ui_EthernetHubPreferencesPag
self.uiEditEthernetHubPushButton.clicked.connect(self._editEthernetHubSlot)
self.uiDeleteEthernetHubPushButton.clicked.connect(self._deleteEthernetHubSlot)
self.uiEthernetHubsTreeWidget.itemSelectionChanged.connect(self._ethernetHubChangedSlot)
self.uiEthernetHubsTreeWidget.itemDoubleClicked.connect(self._editEthernetHubSlot)
def _createSectionItem(self, name):
"""
@@ -81,7 +83,11 @@ class EthernetHubPreferencesPage(QtWidgets.QWidget, Ui_EthernetHubPreferencesPag
QtWidgets.QTreeWidgetItem(section_item, ["Template ID:", ethernet_hub.get("template_id", "none")])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", ethernet_hub["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(ethernet_hub["compute_id"]).name()])
compute_id = ethernet_hub.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass
QtWidgets.QTreeWidgetItem(section_item, ["Number of ports:", str(len(ethernet_hub["ports_mapping"]))])

View File

@@ -127,14 +127,15 @@ class EthernetSwitchConfigurationPage(QtWidgets.QWidget, Ui_ethernetSwitchConfig
if port_type == "qinq":
port_ethertype = self.uiPortEtherTypeComboBox.currentText()
else:
port_ethertype = ""
port_ethertype = None
if port in self._ports:
# update a given entry in the tree widget
item = self.uiPortsTreeWidget.findItems(str(port), QtCore.Qt.MatchFixedString)[0]
item.setText(1, str(vlan))
item.setText(2, port_type)
item.setText(3, port_ethertype)
if port_ethertype:
item.setText(3, port_ethertype)
else:
# add a new entry in the tree widget
@@ -142,7 +143,8 @@ class EthernetSwitchConfigurationPage(QtWidgets.QWidget, Ui_ethernetSwitchConfig
item.setText(0, str(port))
item.setText(1, str(vlan))
item.setText(2, port_type)
item.setText(3, port_ethertype)
if port_ethertype:
item.setText(3, port_ethertype)
self.uiPortsTreeWidget.addTopLevelItem(item)
self._ports[port] = {"name": "Ethernet{}".format(port),
@@ -224,7 +226,9 @@ class EthernetSwitchConfigurationPage(QtWidgets.QWidget, Ui_ethernetSwitchConfig
item.setText(0, str(port_info["port_number"]))
item.setText(1, str(port_info.get("vlan", 1)))
item.setText(2, port_info.get("type", "access"))
item.setText(3, port_info.get("ethertype", ""))
port_ethertype = port_info.get("ethertype")
if port_ethertype:
item.setText(3, port_ethertype)
self.uiPortsTreeWidget.addTopLevelItem(item)
self._ports[port_info["port_number"]] = port_info

View File

@@ -53,6 +53,7 @@ class EthernetSwitchPreferencesPage(QtWidgets.QWidget, Ui_EthernetSwitchPreferen
self.uiEditEthernetSwitchPushButton.clicked.connect(self._editEthernetSwitchSlot)
self.uiDeleteEthernetSwitchPushButton.clicked.connect(self._deleteEthernetSwitchSlot)
self.uiEthernetSwitchesTreeWidget.itemSelectionChanged.connect(self._ethernetSwitchChangedSlot)
self.uiEthernetSwitchesTreeWidget.itemDoubleClicked.connect(self._editEthernetSwitchSlot)
def _createSectionItem(self, name):
"""
@@ -81,7 +82,11 @@ class EthernetSwitchPreferencesPage(QtWidgets.QWidget, Ui_EthernetSwitchPreferen
QtWidgets.QTreeWidgetItem(section_item, ["Template ID:", ethernet_switch.get("template_id", "none")])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", ethernet_switch["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(ethernet_switch["compute_id"]).name()])
compute_id = ethernet_switch.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass

View File

@@ -34,12 +34,13 @@ BUILTIN_SETTINGS = {
CLOUD_SETTINGS = {
"name": "",
"usage": "",
"remote_console_host": "127.0.0.1",
"remote_console_port": 23,
"remote_console_type": "none",
"remote_console_http_path": "/",
"default_name_format": "Cloud{0}",
"symbol": ":/symbols/cloud.svg",
"symbol": "cloud",
"category": Node.end_devices,
"ports_mapping": [],
"node_type": "cloud"
@@ -48,7 +49,7 @@ CLOUD_SETTINGS = {
ETHERNET_HUB_SETTINGS = {
"name": "",
"default_name_format": "Hub{0}",
"symbol": ":/symbols/hub.svg",
"symbol": "hub",
"category": Node.switches,
"ports_mapping": [],
"node_type": "ethernet_hub"
@@ -57,7 +58,7 @@ ETHERNET_HUB_SETTINGS = {
ETHERNET_SWITCH_SETTINGS = {
"name": "",
"default_name_format": "Switch{0}",
"symbol": ":/symbols/ethernet_switch.svg",
"symbol": "ethernet_switch",
"category": Node.switches,
"console_type": "none",
"ports_mapping": [],

View File

@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>979</width>
<height>564</height>
<width>1034</width>
<height>575</height>
</rect>
</property>
<property name="windowTitle">
@@ -555,6 +555,16 @@
<zorder>uiConsoleTypeLabel</zorder>
<zorder>uiConsoleTypeComboBox</zorder>
</widget>
<widget class="QWidget" name="tab">
<attribute name="title">
<string>Usage</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QPlainTextEdit" name="uiUsageTextEdit"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>

View File

@@ -2,16 +2,19 @@
# Form implementation generated from reading ui file '/home/grossmj/PycharmProjects/gns3-gui/gns3/modules/builtin/ui/cloud_configuration_page.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING! All changes made in this file will be lost!
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_cloudConfigPageWidget(object):
def setupUi(self, cloudConfigPageWidget):
cloudConfigPageWidget.setObjectName("cloudConfigPageWidget")
cloudConfigPageWidget.resize(979, 564)
cloudConfigPageWidget.resize(1034, 575)
self.verticalLayout = QtWidgets.QVBoxLayout(cloudConfigPageWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.uiTabWidget = QtWidgets.QTabWidget(cloudConfigPageWidget)
@@ -281,6 +284,14 @@ class Ui_cloudConfigPageWidget(object):
self.uiConsoleTypeLabel.raise_()
self.uiConsoleTypeComboBox.raise_()
self.uiTabWidget.addTab(self.MiscTab, "")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.tab)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.uiUsageTextEdit = QtWidgets.QPlainTextEdit(self.tab)
self.uiUsageTextEdit.setObjectName("uiUsageTextEdit")
self.verticalLayout_3.addWidget(self.uiUsageTextEdit)
self.uiTabWidget.addTab(self.tab, "")
self.verticalLayout.addWidget(self.uiTabWidget)
self.retranslateUi(cloudConfigPageWidget)
@@ -335,4 +346,4 @@ class Ui_cloudConfigPageWidget(object):
self.uiConsoleTypeComboBox.setItemText(4, _translate("cloudConfigPageWidget", "https"))
self.uiConsoleTypeComboBox.setItemText(5, _translate("cloudConfigPageWidget", "none"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.MiscTab), _translate("cloudConfigPageWidget", "Misc."))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.tab), _translate("cloudConfigPageWidget", "Usage"))

View File

@@ -39,7 +39,7 @@ class DockerVMWizard(VMWizard, Ui_DockerVMWizard):
super().__init__(docker_containers, parent)
self._docker_containers = docker_containers
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/icons/docker.png"))
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/symbols/docker_guest.svg"))
self.uiNewImageRadioButton.setChecked(True)
self._existingImageRadioButtonToggledSlot(False)

View File

@@ -45,14 +45,17 @@ class DockerVM(Node):
"custom_adapters": DOCKER_CONTAINER_SETTINGS["custom_adapters"],
"start_command": DOCKER_CONTAINER_SETTINGS["start_command"],
"environment": DOCKER_CONTAINER_SETTINGS["environment"],
"aux": None,
"console_type": DOCKER_CONTAINER_SETTINGS["console_type"],
"console_auto_start": DOCKER_CONTAINER_SETTINGS["console_auto_start"],
"aux_type": DOCKER_CONTAINER_SETTINGS["aux_type"],
"console_resolution": DOCKER_CONTAINER_SETTINGS["console_resolution"],
"console_http_port": DOCKER_CONTAINER_SETTINGS["console_http_port"],
"console_http_path": DOCKER_CONTAINER_SETTINGS["console_http_path"],
"extra_hosts": DOCKER_CONTAINER_SETTINGS["extra_hosts"],
"extra_volumes": DOCKER_CONTAINER_SETTINGS["extra_volumes"]}
"extra_volumes": DOCKER_CONTAINER_SETTINGS["extra_volumes"],
"memory": DOCKER_CONTAINER_SETTINGS["memory"],
"cpus": DOCKER_CONTAINER_SETTINGS["cpus"],
}
self.settings().update(docker_vm_settings)
@@ -68,6 +71,7 @@ class DockerVM(Node):
Local ID is {id} and server ID is {node_id}
Docker image is "{image}"
Console is on port {console} and type is {console_type}
Aux console is on port {aux} and type is {aux_type}
""".format(name=self.name(),
id=self.id(),
node_id=self._node_id,
@@ -76,6 +80,8 @@ class DockerVM(Node):
port=self.compute().port(),
console=self._settings["console"],
console_type=self._settings["console_type"],
aux=self._settings["aux"],
aux_type=self._settings["aux_type"],
image=self._settings["image"])
port_info = ""

View File

@@ -100,11 +100,14 @@ class DockerVMConfigurationPage(QtWidgets.QWidget, Ui_dockerVMConfigPageWidget):
self.uiEnvironmentTextEdit.setText(settings["environment"])
self.uiConsoleTypeComboBox.setCurrentIndex(self.uiConsoleTypeComboBox.findText(settings["console_type"]))
self.uiConsoleAutoStartCheckBox.setChecked(settings["console_auto_start"])
self.uiAuxTypeComboBox.setCurrentIndex(self.uiAuxTypeComboBox.findText(settings["aux_type"]))
self.uiConsoleResolutionComboBox.setCurrentIndex(self.uiConsoleResolutionComboBox.findText(settings["console_resolution"]))
self.uiConsoleHttpPortSpinBox.setValue(settings["console_http_port"])
self.uiHttpConsolePathLineEdit.setText(settings["console_http_path"])
self.uiExtraHostsTextEdit.setPlainText(settings["extra_hosts"])
self.uiExtraVolumeTextEdit.setPlainText("\n".join(settings["extra_volumes"]))
self.uiMaxMemorySpinBox.setValue(settings["memory"])
self.uiMaxCPUsDoubleSpinBox.setValue(settings["cpus"])
if not group:
self.uiNameLineEdit.setText(settings["name"])
@@ -172,12 +175,15 @@ class DockerVMConfigurationPage(QtWidgets.QWidget, Ui_dockerVMConfigPageWidget):
settings["environment"] = self.uiEnvironmentTextEdit.toPlainText()
settings["console_type"] = self.uiConsoleTypeComboBox.currentText()
settings["console_auto_start"] = self.uiConsoleAutoStartCheckBox.isChecked()
settings["aux_type"] = self.uiAuxTypeComboBox.currentText()
settings["console_resolution"] = self.uiConsoleResolutionComboBox.currentText()
settings["console_http_port"] = self.uiConsoleHttpPortSpinBox.value()
settings["console_http_path"] = self.uiHttpConsolePathLineEdit.text()
settings["extra_hosts"] = self.uiExtraHostsTextEdit.toPlainText()
# only tidy input here, validation is performed server side
settings["extra_volumes"] = [ y for x in self.uiExtraVolumeTextEdit.toPlainText().split("\n") for y in [ x.strip() ] if y ]
settings["memory"] = self.uiMaxMemorySpinBox.value()
settings["cpus"] = self.uiMaxCPUsDoubleSpinBox.value()
if not group:
adapters = self.uiAdapterSpinBox.value()

View File

@@ -52,6 +52,7 @@ class DockerVMPreferencesPage(QtWidgets.QWidget, Ui_DockerVMPreferencesPageWidge
self.uiEditDockerVMPushButton.clicked.connect(self._dockerImageEditSlot)
self.uiDeleteDockerVMPushButton.clicked.connect(self._dockerImageDeleteSlot)
self.uiDockerVMsTreeWidget.itemSelectionChanged.connect(self._dockerImageChangedSlot)
self.uiDockerVMsTreeWidget.itemDoubleClicked.connect(self._dockerImageEditSlot)
def _createSectionItem(self, name):
"""
@@ -80,11 +81,16 @@ class DockerVMPreferencesPage(QtWidgets.QWidget, Ui_DockerVMPreferencesPageWidge
QtWidgets.QTreeWidgetItem(section_item, ["Template ID:", docker_container.get("template_id", "none")])
QtWidgets.QTreeWidgetItem(section_item, ["Image name:", docker_container["image"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(docker_container["compute_id"]).name()])
compute_id = docker_container.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass
QtWidgets.QTreeWidgetItem(section_item, ["Console type:", str(docker_container["console_type"])])
QtWidgets.QTreeWidgetItem(section_item, ["Auto start console:", "{}".format(docker_container["console_auto_start"])])
QtWidgets.QTreeWidgetItem(section_item, ["Auxiliary console type:", str(docker_container["aux_type"])])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", docker_container["default_name_format"]])
QtWidgets.QTreeWidgetItem(section_item, ["Adapters:", str(docker_container["adapters"])])
if docker_container["start_command"]:

View File

@@ -29,7 +29,7 @@ DOCKER_SETTINGS = {
DOCKER_CONTAINER_SETTINGS = {
"default_name_format": "{name}-{0}",
"usage": "",
"symbol": ":/symbols/docker_guest.svg",
"symbol": "docker_guest",
"category": Node.end_devices,
"start_command": "",
"name": "",
@@ -39,10 +39,13 @@ DOCKER_CONTAINER_SETTINGS = {
"environment": "",
"console_type": "telnet",
"console_auto_start": False,
"aux_type": "none",
"console_resolution": "1024x768",
"console_http_port": 80,
"console_http_path": "/",
"extra_hosts": "",
"extra_volumes": [],
"memory": 0,
"cpus": 0,
"node_type": "docker"
}

View File

@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>938</width>
<height>872</height>
<width>961</width>
<height>1126</height>
</rect>
</property>
<property name="windowTitle">
@@ -116,14 +116,14 @@
</property>
</widget>
</item>
<item row="7" column="0">
<item row="10" column="0">
<widget class="QLabel" name="uiConsoleTypeLabel">
<property name="text">
<string>Console type:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<item row="10" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetNoConstraint</enum>
@@ -166,20 +166,35 @@
</item>
</layout>
</item>
<item row="8" column="0">
<item row="12" column="0">
<widget class="QLabel" name="uiConsoleResolutionLabel">
<property name="text">
<string>VNC console resolution:</string>
</property>
</widget>
</item>
<item row="8" column="1">
<item row="12" column="1">
<widget class="QComboBox" name="uiConsoleResolutionComboBox">
<item>
<property name="text">
<string>2560x1440</string>
</property>
</item>
<item>
<property name="text">
<string>1920x1080</string>
</property>
</item>
<item>
<property name="text">
<string>1680x1050</string>
</property>
</item>
<item>
<property name="text">
<string>1440x900</string>
</property>
</item>
<item>
<property name="text">
<string>1366x768</string>
@@ -212,14 +227,14 @@
</item>
</widget>
</item>
<item row="9" column="0">
<item row="13" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>HTTP port in the container:</string>
</property>
</widget>
</item>
<item row="9" column="1">
<item row="13" column="1">
<widget class="QSpinBox" name="uiConsoleHttpPortSpinBox">
<property name="minimum">
<number>1</number>
@@ -229,17 +244,17 @@
</property>
</widget>
</item>
<item row="10" column="0">
<item row="14" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>HTTP path:</string>
</property>
</widget>
</item>
<item row="10" column="1">
<item row="14" column="1">
<widget class="QLineEdit" name="uiHttpConsolePathLineEdit"/>
</item>
<item row="11" column="0">
<item row="15" column="0">
<widget class="QLabel" name="uiEnvironmentLabel">
<property name="text">
<string>Environment variables:
@@ -253,23 +268,81 @@
</property>
</widget>
</item>
<item row="11" column="1">
<item row="15" column="1">
<widget class="QTextEdit" name="uiEnvironmentTextEdit"/>
</item>
<item row="12" column="0">
<item row="16" column="0">
<widget class="QLabel" name="uiNetworkConfigLabel">
<property name="text">
<string>Network configuration</string>
</property>
</widget>
</item>
<item row="12" column="1">
<item row="16" column="1">
<widget class="QPushButton" name="uiNetworkConfigEditButton">
<property name="text">
<string>Edit</string>
</property>
</widget>
</item>
<item row="8" column="0">
<widget class="QLabel" name="uiMaxCPUsLabel">
<property name="text">
<string>Maximum CPUs:</string>
</property>
</widget>
</item>
<item row="8" column="1">
<widget class="QDoubleSpinBox" name="uiMaxCPUsDoubleSpinBox">
<property name="decimals">
<number>1</number>
</property>
<property name="singleStep">
<double>0.100000000000000</double>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="uiMaxMemoryLabel">
<property name="text">
<string>Maximum memory:</string>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QSpinBox" name="uiMaxMemorySpinBox">
<property name="suffix">
<string> MB</string>
</property>
<property name="maximum">
<number>65535</number>
</property>
<property name="singleStep">
<number>32</number>
</property>
</widget>
</item>
<item row="11" column="0">
<widget class="QLabel" name="uiAuxTypeLabel">
<property name="text">
<string>Auxiliary console type:</string>
</property>
</widget>
</item>
<item row="11" column="1">
<widget class="QComboBox" name="uiAuxTypeComboBox">
<item>
<property name="text">
<string>telnet</string>
</property>
</item>
<item>
<property name="text">
<string>none</string>
</property>
</item>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_2">

View File

@@ -2,16 +2,19 @@
# Form implementation generated from reading ui file '/home/grossmj/PycharmProjects/gns3-gui/gns3/modules/docker/ui/docker_vm_configuration_page.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
# Created by: PyQt5 UI code generator 5.15.7
#
# WARNING! All changes made in this file will be lost!
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_dockerVMConfigPageWidget(object):
def setupUi(self, dockerVMConfigPageWidget):
dockerVMConfigPageWidget.setObjectName("dockerVMConfigPageWidget")
dockerVMConfigPageWidget.resize(938, 872)
dockerVMConfigPageWidget.resize(961, 1126)
self.verticalLayout = QtWidgets.QVBoxLayout(dockerVMConfigPageWidget)
self.verticalLayout.setObjectName("verticalLayout")
self.uiTabWidget = QtWidgets.QTabWidget(dockerVMConfigPageWidget)
@@ -72,7 +75,7 @@ class Ui_dockerVMConfigPageWidget(object):
self.gridLayout.addWidget(self.uiCustomAdaptersConfigurationPushButton, 6, 1, 1, 1)
self.uiConsoleTypeLabel = QtWidgets.QLabel(self.tab)
self.uiConsoleTypeLabel.setObjectName("uiConsoleTypeLabel")
self.gridLayout.addWidget(self.uiConsoleTypeLabel, 7, 0, 1, 1)
self.gridLayout.addWidget(self.uiConsoleTypeLabel, 10, 0, 1, 1)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetNoConstraint)
self.horizontalLayout.setObjectName("horizontalLayout")
@@ -87,10 +90,10 @@ class Ui_dockerVMConfigPageWidget(object):
self.uiConsoleAutoStartCheckBox = QtWidgets.QCheckBox(self.tab)
self.uiConsoleAutoStartCheckBox.setObjectName("uiConsoleAutoStartCheckBox")
self.horizontalLayout.addWidget(self.uiConsoleAutoStartCheckBox)
self.gridLayout.addLayout(self.horizontalLayout, 7, 1, 1, 1)
self.gridLayout.addLayout(self.horizontalLayout, 10, 1, 1, 1)
self.uiConsoleResolutionLabel = QtWidgets.QLabel(self.tab)
self.uiConsoleResolutionLabel.setObjectName("uiConsoleResolutionLabel")
self.gridLayout.addWidget(self.uiConsoleResolutionLabel, 8, 0, 1, 1)
self.gridLayout.addWidget(self.uiConsoleResolutionLabel, 12, 0, 1, 1)
self.uiConsoleResolutionComboBox = QtWidgets.QComboBox(self.tab)
self.uiConsoleResolutionComboBox.setObjectName("uiConsoleResolutionComboBox")
self.uiConsoleResolutionComboBox.addItem("")
@@ -100,35 +103,62 @@ class Ui_dockerVMConfigPageWidget(object):
self.uiConsoleResolutionComboBox.addItem("")
self.uiConsoleResolutionComboBox.addItem("")
self.uiConsoleResolutionComboBox.addItem("")
self.gridLayout.addWidget(self.uiConsoleResolutionComboBox, 8, 1, 1, 1)
self.uiConsoleResolutionComboBox.addItem("")
self.uiConsoleResolutionComboBox.addItem("")
self.uiConsoleResolutionComboBox.addItem("")
self.gridLayout.addWidget(self.uiConsoleResolutionComboBox, 12, 1, 1, 1)
self.label = QtWidgets.QLabel(self.tab)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 9, 0, 1, 1)
self.gridLayout.addWidget(self.label, 13, 0, 1, 1)
self.uiConsoleHttpPortSpinBox = QtWidgets.QSpinBox(self.tab)
self.uiConsoleHttpPortSpinBox.setMinimum(1)
self.uiConsoleHttpPortSpinBox.setMaximum(65535)
self.uiConsoleHttpPortSpinBox.setObjectName("uiConsoleHttpPortSpinBox")
self.gridLayout.addWidget(self.uiConsoleHttpPortSpinBox, 9, 1, 1, 1)
self.gridLayout.addWidget(self.uiConsoleHttpPortSpinBox, 13, 1, 1, 1)
self.label_2 = QtWidgets.QLabel(self.tab)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 10, 0, 1, 1)
self.gridLayout.addWidget(self.label_2, 14, 0, 1, 1)
self.uiHttpConsolePathLineEdit = QtWidgets.QLineEdit(self.tab)
self.uiHttpConsolePathLineEdit.setObjectName("uiHttpConsolePathLineEdit")
self.gridLayout.addWidget(self.uiHttpConsolePathLineEdit, 10, 1, 1, 1)
self.gridLayout.addWidget(self.uiHttpConsolePathLineEdit, 14, 1, 1, 1)
self.uiEnvironmentLabel = QtWidgets.QLabel(self.tab)
self.uiEnvironmentLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.uiEnvironmentLabel.setWordWrap(False)
self.uiEnvironmentLabel.setObjectName("uiEnvironmentLabel")
self.gridLayout.addWidget(self.uiEnvironmentLabel, 11, 0, 1, 1)
self.gridLayout.addWidget(self.uiEnvironmentLabel, 15, 0, 1, 1)
self.uiEnvironmentTextEdit = QtWidgets.QTextEdit(self.tab)
self.uiEnvironmentTextEdit.setObjectName("uiEnvironmentTextEdit")
self.gridLayout.addWidget(self.uiEnvironmentTextEdit, 11, 1, 1, 1)
self.gridLayout.addWidget(self.uiEnvironmentTextEdit, 15, 1, 1, 1)
self.uiNetworkConfigLabel = QtWidgets.QLabel(self.tab)
self.uiNetworkConfigLabel.setObjectName("uiNetworkConfigLabel")
self.gridLayout.addWidget(self.uiNetworkConfigLabel, 12, 0, 1, 1)
self.gridLayout.addWidget(self.uiNetworkConfigLabel, 16, 0, 1, 1)
self.uiNetworkConfigEditButton = QtWidgets.QPushButton(self.tab)
self.uiNetworkConfigEditButton.setObjectName("uiNetworkConfigEditButton")
self.gridLayout.addWidget(self.uiNetworkConfigEditButton, 12, 1, 1, 1)
self.gridLayout.addWidget(self.uiNetworkConfigEditButton, 16, 1, 1, 1)
self.uiMaxCPUsLabel = QtWidgets.QLabel(self.tab)
self.uiMaxCPUsLabel.setObjectName("uiMaxCPUsLabel")
self.gridLayout.addWidget(self.uiMaxCPUsLabel, 8, 0, 1, 1)
self.uiMaxCPUsDoubleSpinBox = QtWidgets.QDoubleSpinBox(self.tab)
self.uiMaxCPUsDoubleSpinBox.setDecimals(1)
self.uiMaxCPUsDoubleSpinBox.setSingleStep(0.1)
self.uiMaxCPUsDoubleSpinBox.setObjectName("uiMaxCPUsDoubleSpinBox")
self.gridLayout.addWidget(self.uiMaxCPUsDoubleSpinBox, 8, 1, 1, 1)
self.uiMaxMemoryLabel = QtWidgets.QLabel(self.tab)
self.uiMaxMemoryLabel.setObjectName("uiMaxMemoryLabel")
self.gridLayout.addWidget(self.uiMaxMemoryLabel, 7, 0, 1, 1)
self.uiMaxMemorySpinBox = QtWidgets.QSpinBox(self.tab)
self.uiMaxMemorySpinBox.setMaximum(65535)
self.uiMaxMemorySpinBox.setSingleStep(32)
self.uiMaxMemorySpinBox.setObjectName("uiMaxMemorySpinBox")
self.gridLayout.addWidget(self.uiMaxMemorySpinBox, 7, 1, 1, 1)
self.uiAuxTypeLabel = QtWidgets.QLabel(self.tab)
self.uiAuxTypeLabel.setObjectName("uiAuxTypeLabel")
self.gridLayout.addWidget(self.uiAuxTypeLabel, 11, 0, 1, 1)
self.uiAuxTypeComboBox = QtWidgets.QComboBox(self.tab)
self.uiAuxTypeComboBox.setObjectName("uiAuxTypeComboBox")
self.uiAuxTypeComboBox.addItem("")
self.uiAuxTypeComboBox.addItem("")
self.gridLayout.addWidget(self.uiAuxTypeComboBox, 11, 1, 1, 1)
self.uiTabWidget.addTab(self.tab, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
@@ -190,19 +220,28 @@ class Ui_dockerVMConfigPageWidget(object):
self.uiConsoleTypeComboBox.setItemText(4, _translate("dockerVMConfigPageWidget", "none"))
self.uiConsoleAutoStartCheckBox.setText(_translate("dockerVMConfigPageWidget", "Auto start console"))
self.uiConsoleResolutionLabel.setText(_translate("dockerVMConfigPageWidget", "VNC console resolution:"))
self.uiConsoleResolutionComboBox.setItemText(0, _translate("dockerVMConfigPageWidget", "1920x1080"))
self.uiConsoleResolutionComboBox.setItemText(1, _translate("dockerVMConfigPageWidget", "1366x768"))
self.uiConsoleResolutionComboBox.setItemText(2, _translate("dockerVMConfigPageWidget", "1280x1024"))
self.uiConsoleResolutionComboBox.setItemText(3, _translate("dockerVMConfigPageWidget", "1280x800"))
self.uiConsoleResolutionComboBox.setItemText(4, _translate("dockerVMConfigPageWidget", "1024x768"))
self.uiConsoleResolutionComboBox.setItemText(5, _translate("dockerVMConfigPageWidget", "800x600"))
self.uiConsoleResolutionComboBox.setItemText(6, _translate("dockerVMConfigPageWidget", "640x480"))
self.uiConsoleResolutionComboBox.setItemText(0, _translate("dockerVMConfigPageWidget", "2560x1440"))
self.uiConsoleResolutionComboBox.setItemText(1, _translate("dockerVMConfigPageWidget", "1920x1080"))
self.uiConsoleResolutionComboBox.setItemText(2, _translate("dockerVMConfigPageWidget", "1680x1050"))
self.uiConsoleResolutionComboBox.setItemText(3, _translate("dockerVMConfigPageWidget", "1440x900"))
self.uiConsoleResolutionComboBox.setItemText(4, _translate("dockerVMConfigPageWidget", "1366x768"))
self.uiConsoleResolutionComboBox.setItemText(5, _translate("dockerVMConfigPageWidget", "1280x1024"))
self.uiConsoleResolutionComboBox.setItemText(6, _translate("dockerVMConfigPageWidget", "1280x800"))
self.uiConsoleResolutionComboBox.setItemText(7, _translate("dockerVMConfigPageWidget", "1024x768"))
self.uiConsoleResolutionComboBox.setItemText(8, _translate("dockerVMConfigPageWidget", "800x600"))
self.uiConsoleResolutionComboBox.setItemText(9, _translate("dockerVMConfigPageWidget", "640x480"))
self.label.setText(_translate("dockerVMConfigPageWidget", "HTTP port in the container:"))
self.label_2.setText(_translate("dockerVMConfigPageWidget", "HTTP path:"))
self.uiEnvironmentLabel.setText(_translate("dockerVMConfigPageWidget", "Environment variables:\n"
"(KEY=VALUE, one per line)"))
self.uiNetworkConfigLabel.setText(_translate("dockerVMConfigPageWidget", "Network configuration"))
self.uiNetworkConfigEditButton.setText(_translate("dockerVMConfigPageWidget", "Edit"))
self.uiMaxCPUsLabel.setText(_translate("dockerVMConfigPageWidget", "Maximum CPUs:"))
self.uiMaxMemoryLabel.setText(_translate("dockerVMConfigPageWidget", "Maximum memory:"))
self.uiMaxMemorySpinBox.setSuffix(_translate("dockerVMConfigPageWidget", " MB"))
self.uiAuxTypeLabel.setText(_translate("dockerVMConfigPageWidget", "Auxiliary console type:"))
self.uiAuxTypeComboBox.setItemText(0, _translate("dockerVMConfigPageWidget", "telnet"))
self.uiAuxTypeComboBox.setItemText(1, _translate("dockerVMConfigPageWidget", "none"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.tab), _translate("dockerVMConfigPageWidget", "General settings"))
self.uiExtraHostsLabel.setText(_translate("dockerVMConfigPageWidget", "Extra hosts added\n"
"to the /etc/hosts file.\n"
@@ -217,4 +256,3 @@ class Ui_dockerVMConfigPageWidget(object):
self.uiExtraVolumeTextEdit.setPlaceholderText(_translate("dockerVMConfigPageWidget", "e.g. /etc/sysctl.d"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.tab_2), _translate("dockerVMConfigPageWidget", "Advanced"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.tab_3), _translate("dockerVMConfigPageWidget", "Usage"))

View File

@@ -25,7 +25,6 @@ import hashlib
from gns3.local_config import LocalConfig
from gns3.image_manager import ImageManager
from gns3.local_server_config import LocalServerConfig
from gns3.controller import Controller
from gns3.template_manager import TemplateManager
from gns3.template import Template
@@ -145,18 +144,19 @@ class Dynamips(Module):
# save the settings
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
# save some settings to the local server config file
server_settings = {
"allocate_aux_console_ports": self._settings["allocate_aux_console_ports"],
"ghost_ios_support": self._settings["ghost_ios_support"],
"sparse_memory_support": self._settings["sparse_memory_support"],
"mmap_support": self._settings["mmap_support"],
}
if self._settings["dynamips_path"]:
server_settings["dynamips_path"] = os.path.normpath(self._settings["dynamips_path"])
config = LocalServerConfig.instance()
config.saveSettings(self.__class__.__name__, server_settings)
# FIXME: handle server side config
# # save some settings to the local server config file
# server_settings = {
# "allocate_aux_console_ports": self._settings["allocate_aux_console_ports"],
# "ghost_ios_support": self._settings["ghost_ios_support"],
# "sparse_memory_support": self._settings["sparse_memory_support"],
# "mmap_support": self._settings["mmap_support"],
# }
#
# if self._settings["dynamips_path"]:
# server_settings["dynamips_path"] = os.path.normpath(self._settings["dynamips_path"])
# config = LocalServerConfig.instance()
# config.saveSettings(self.__class__.__name__, server_settings)
def updateImageIdlepc(self, image_path, idlepc):
"""

View File

@@ -220,13 +220,13 @@ class IOSRouterWizard(VMWithImagesWizard, Ui_IOSRouterWizard):
ram = self.uiRamSpinBox.value()
Controller.instance().postCompute("/auto_idlepc",
self._compute_id,
self._computeAutoIdlepcCallback,
callback=self._computeAutoIdlepcCallback,
timeout=None,
body={
"image": image,
"platform": platform,
"ram": ram})
self.uiIdlePCFinderPushButton.setEnabled(False)
"ram": ram},
wait=True)
def _etherSwitchSlot(self, state):
"""
@@ -316,7 +316,7 @@ class IOSRouterWizard(VMWithImagesWizard, Ui_IOSRouterWizard):
super().initializePage(page_id)
if self.page(page_id) == self.uiIOSImageWizardPage:
self.loadImagesList("/dynamips/images")
self.loadImagesList("ios")
elif self.page(page_id) == self.uiNameWizardPage:
self._prefillPlatform()
self.uiNameLineEdit.setText(self.uiPlatformComboBox.currentText())

View File

@@ -71,6 +71,7 @@ class Router(Node):
"console_type": "telnet",
"console_auto_start": False,
"aux": None,
"aux_type": "none",
"mac_addr": None,
"system_id": "FTX0945W0MY",
"slot0": None,
@@ -101,11 +102,14 @@ class Router(Node):
"""
log.debug("{} is requesting Idle-PC proposals".format(self.name()))
self.controllerHttpGet("/nodes/{node_id}/dynamips/idlepc_proposals".format(node_id=self._node_id),
callback,
timeout=240,
context={"router": self},
progressText="Computing Idle-PC values, please wait...")
self.controllerHttpGet(
"/nodes/{node_id}/dynamips/idlepc_proposals".format(node_id=self._node_id),
callback,
context={"router": self},
progress_text="Computing Idle-PC values, please wait...",
timeout=240,
wait=True
)
def computeAutoIdlepc(self, callback):
"""
@@ -113,11 +117,14 @@ class Router(Node):
"""
log.debug("{} is requesting Idle-PC proposals".format(self.name()))
self.controllerHttpGet("/nodes/{node_id}/dynamips/auto_idlepc".format(node_id=self._node_id),
callback,
timeout=240,
context={"router": self},
progressText="Computing Idle-PC values, please wait...")
self.controllerHttpGet(
"/nodes/{node_id}/dynamips/auto_idlepc".format(node_id=self._node_id),
callback,
context={"router": self},
progress_text="Computing Idle-PC values, please wait...",
timeout=240,
wait=True
)
def idlepc(self):
"""
@@ -242,7 +249,8 @@ class Router(Node):
Local ID is {id} and server ID is {node_id}
Dynamips ID is {dynamips_id}
Hardware is Dynamips emulated Cisco {platform} {specific_info} with {ram}MB RAM and {nvram}KB NVRAM
Console is on port {console} and type is {console_type}, AUX console is on port {aux}
Console is on port {console} and type is {console_type}
Auxiliary console is on port {aux} and type is {aux_type}
IOS image is "{image_name}"
{idlepc_info}
PCMCIA disks: disk0 is {disk0}MB and disk1 is {disk1}MB
@@ -260,6 +268,7 @@ class Router(Node):
console=self._settings["console"],
console_type=self._settings["console_type"],
aux=self._settings["aux"],
aux_type=self._settings["aux_type"],
image_name=os.path.basename(self._settings["image"]),
idlepc_info=idlepc_info,
disk0=self._settings["disk0"],
@@ -298,23 +307,6 @@ class Router(Node):
from ..pages.ios_router_configuration_page import IOSRouterConfigurationPage
return IOSRouterConfigurationPage
@staticmethod
def validateHostname(hostname):
"""
Checks if the hostname is valid.
:param hostname: hostname to check
:returns: boolean
"""
# IOS names must start with a letter, end with a letter or digit, and
# have as interior characters only letters, digits, and hyphens.
# They must be 63 characters or fewer.
if re.search(r"""^[\-\w]+$""", hostname) and len(hostname) <= 63:
return True
return False
@staticmethod
def defaultSymbol():
"""

View File

@@ -374,6 +374,11 @@ class IOSRouterConfigurationPage(QtWidgets.QWidget, Ui_iosRouterConfigPageWidget
self.uiConsoleAutoStartCheckBox.setChecked(settings["console_auto_start"])
# load the auxiliary console type
index = self.uiAuxTypeComboBox.findText(settings["aux_type"])
if index != -1:
self.uiAuxTypeComboBox.setCurrentIndex(index)
# load the memories and disks settings
self.uiRamSpinBox.setValue(settings["ram"])
self.uiNvramSpinBox.setValue(settings["nvram"])
@@ -488,8 +493,6 @@ class IOSRouterConfigurationPage(QtWidgets.QWidget, Ui_iosRouterConfigPageWidget
name = self.uiNameLineEdit.text()
if not name:
QtWidgets.QMessageBox.critical(self, "Name", "IOS router name cannot be empty!")
elif node and not node.validateHostname(name):
QtWidgets.QMessageBox.critical(self, "Name", "Invalid name detected for IOS router: {}".format(name))
else:
settings["name"] = name
@@ -579,6 +582,9 @@ class IOSRouterConfigurationPage(QtWidgets.QWidget, Ui_iosRouterConfigPageWidget
settings["console_type"] = self.uiConsoleTypeComboBox.currentText().lower()
settings["console_auto_start"] = self.uiConsoleAutoStartCheckBox.isChecked()
# save auxiliary console type
settings["aux_type"] = self.uiAuxTypeComboBox.currentText().lower()
# save the memories and disks settings
settings["ram"] = self.uiRamSpinBox.value()
settings["nvram"] = self.uiNvramSpinBox.value()

View File

@@ -70,6 +70,7 @@ class IOSRouterPreferencesPage(QtWidgets.QWidget, Ui_IOSRouterPreferencesPageWid
self.uiDeleteIOSRouterPushButton.clicked.connect(self._iosRouterDeleteSlot)
self.uiIOSRoutersTreeWidget.itemSelectionChanged.connect(self._iosRouterChangedSlot)
self.uiDecompressIOSPushButton.clicked.connect(self._decompressIOSSlot)
self.uiIOSRoutersTreeWidget.itemDoubleClicked.connect(self._iosRouterEditSlot)
def _iosRouterChangedSlot(self):
"""
@@ -385,7 +386,11 @@ class IOSRouterPreferencesPage(QtWidgets.QWidget, Ui_IOSRouterPreferencesPageWid
QtWidgets.QTreeWidgetItem(section_item, ["Template ID:", ios_router.get("template_id", "none")])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", ios_router["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(ios_router["compute_id"]).name()])
compute_id = ios_router.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass
QtWidgets.QTreeWidgetItem(section_item, ["Platform:", ios_router["platform"]])
@@ -394,6 +399,7 @@ class IOSRouterPreferencesPage(QtWidgets.QWidget, Ui_IOSRouterPreferencesPageWid
QtWidgets.QTreeWidgetItem(section_item, ["Image:", ios_router["image"]])
QtWidgets.QTreeWidgetItem(section_item, ["Console type:", ios_router["console_type"]])
QtWidgets.QTreeWidgetItem(section_item, ["Auto start console:", "{}".format(ios_router["console_auto_start"])])
QtWidgets.QTreeWidgetItem(section_item, ["Auxiliary console type:", ios_router["aux_type"]])
if ios_router["idlepc"]:
QtWidgets.QTreeWidgetItem(section_item, ["Idle-PC:", ios_router["idlepc"]])
if ios_router["startup_config"]:

View File

@@ -34,12 +34,13 @@ IOS_ROUTER_SETTINGS = {
"default_name_format": "R{0}",
"usage": "",
"image": "",
"symbol": ":/symbols/router.svg",
"symbol": "router",
"category": Node.routers,
"startup_config": "",
"private_config": "",
"console_type": "telnet",
"console_auto_start": False,
"aux_type": "none",
"platform": "",
"idlepc": "",
"idlemax": 500,

View File

@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>980</width>
<height>734</height>
<width>964</width>
<height>830</height>
</rect>
</property>
<property name="windowTitle">
@@ -250,7 +250,7 @@
</item>
</layout>
</item>
<item row="12" column="1" colspan="2">
<item row="14" column="1" colspan="2">
<spacer>
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -263,6 +263,27 @@
</property>
</spacer>
</item>
<item row="12" column="2">
<widget class="QComboBox" name="uiAuxTypeComboBox">
<item>
<property name="text">
<string>telnet</string>
</property>
</item>
<item>
<property name="text">
<string>none</string>
</property>
</item>
</widget>
</item>
<item row="12" column="0" colspan="2">
<widget class="QLabel" name="uiAuxTypeLabel">
<property name="text">
<string>Aux console type:</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="uiMemoriesPageWidget">
@@ -270,7 +291,16 @@
<string>Memories and disks</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_5">
<property name="margin">
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item row="0" column="0">
@@ -448,7 +478,16 @@
<string>Slots</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="margin">
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item>
@@ -649,7 +688,16 @@
<string>Advanced</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="margin">
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item>
@@ -828,7 +876,16 @@
<string>Environment</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<property name="margin">
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>10</number>
</property>
<item>

View File

@@ -2,16 +2,19 @@
# Form implementation generated from reading ui file '/home/grossmj/PycharmProjects/gns3-gui/gns3/modules/dynamips/ui/ios_router_configuration_page.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING! All changes made in this file will be lost!
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_iosRouterConfigPageWidget(object):
def setupUi(self, iosRouterConfigPageWidget):
iosRouterConfigPageWidget.setObjectName("iosRouterConfigPageWidget")
iosRouterConfigPageWidget.resize(980, 734)
iosRouterConfigPageWidget.resize(964, 830)
self.vboxlayout = QtWidgets.QVBoxLayout(iosRouterConfigPageWidget)
self.vboxlayout.setObjectName("vboxlayout")
self.uiTabWidget = QtWidgets.QTabWidget(iosRouterConfigPageWidget)
@@ -143,7 +146,15 @@ class Ui_iosRouterConfigPageWidget(object):
self.horizontalLayout.addWidget(self.uiConsoleAutoStartCheckBox)
self.gridLayout_2.addLayout(self.horizontalLayout, 11, 2, 1, 1)
spacerItem = QtWidgets.QSpacerItem(263, 151, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout_2.addItem(spacerItem, 12, 1, 1, 2)
self.gridLayout_2.addItem(spacerItem, 14, 1, 1, 2)
self.uiAuxTypeComboBox = QtWidgets.QComboBox(self.uiGeneralPageWidget)
self.uiAuxTypeComboBox.setObjectName("uiAuxTypeComboBox")
self.uiAuxTypeComboBox.addItem("")
self.uiAuxTypeComboBox.addItem("")
self.gridLayout_2.addWidget(self.uiAuxTypeComboBox, 12, 2, 1, 1)
self.uiAuxTypeLabel = QtWidgets.QLabel(self.uiGeneralPageWidget)
self.uiAuxTypeLabel.setObjectName("uiAuxTypeLabel")
self.gridLayout_2.addWidget(self.uiAuxTypeLabel, 12, 0, 1, 2)
self.uiTabWidget.addTab(self.uiGeneralPageWidget, "")
self.uiMemoriesPageWidget = QtWidgets.QWidget()
self.uiMemoriesPageWidget.setObjectName("uiMemoriesPageWidget")
@@ -582,6 +593,9 @@ class Ui_iosRouterConfigPageWidget(object):
self.uiConsoleTypeComboBox.setItemText(0, _translate("iosRouterConfigPageWidget", "telnet"))
self.uiConsoleTypeComboBox.setItemText(1, _translate("iosRouterConfigPageWidget", "none"))
self.uiConsoleAutoStartCheckBox.setText(_translate("iosRouterConfigPageWidget", "Auto start console"))
self.uiAuxTypeComboBox.setItemText(0, _translate("iosRouterConfigPageWidget", "telnet"))
self.uiAuxTypeComboBox.setItemText(1, _translate("iosRouterConfigPageWidget", "none"))
self.uiAuxTypeLabel.setText(_translate("iosRouterConfigPageWidget", "Aux console type:"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.uiGeneralPageWidget), _translate("iosRouterConfigPageWidget", "General"))
self.uiRamLabel.setText(_translate("iosRouterConfigPageWidget", "RAM size:"))
self.uiRamSpinBox.setSuffix(_translate("iosRouterConfigPageWidget", " MiB"))
@@ -639,4 +653,3 @@ class Ui_iosRouterConfigPageWidget(object):
self.uiSensor4SpinBox.setSuffix(_translate("iosRouterConfigPageWidget", " C"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.uiEnvironmentPageWidget), _translate("iosRouterConfigPageWidget", "Environment"))
self.uiTabWidget.setTabText(self.uiTabWidget.indexOf(self.uiUsageTab), _translate("iosRouterConfigPageWidget", "Usage"))

View File

@@ -92,7 +92,7 @@ class IOUDeviceWizard(VMWithImagesWizard, Ui_IOUDeviceWizard):
if self.page(page_id) == self.uiNameWizardPage:
if not self.uiIOUImageToolButton.isEnabled():
QtWidgets.QMessageBox.warning(self, "IOU image", "You have chosen to use a remote server, please provide the path to an IOU image located on this server!")
self.loadImagesList("/iou/images")
self.loadImagesList("iou")
def getSettings(self):
"""

View File

@@ -119,23 +119,6 @@ class IOUDevice(Node):
from .pages.iou_device_configuration_page import iouDeviceConfigurationPage
return iouDeviceConfigurationPage
@staticmethod
def validateHostname(hostname):
"""
Checks if the hostname is valid.
:param hostname: hostname to check
:returns: boolean
"""
# IOS names must start with a letter, end with a letter or digit, and
# have as interior characters only letters, digits, and hyphens.
# They must be 63 characters or fewer.
if re.search(r"""^[\-\w]+$""", hostname) and len(hostname) <= 63:
return True
return False
@staticmethod
def defaultSymbol():
"""

View File

@@ -244,8 +244,6 @@ class iouDeviceConfigurationPage(QtWidgets.QWidget, Ui_iouDeviceConfigPageWidget
name = self.uiNameLineEdit.text()
if not name:
QtWidgets.QMessageBox.critical(self, "Name", "IOU device name cannot be empty!")
elif node and not node.validateHostname(name):
QtWidgets.QMessageBox.critical(self, "Name", "Invalid name detected for IOU device: {}".format(name))
else:
settings["name"] = name

View File

@@ -59,6 +59,7 @@ class IOUDevicePreferencesPage(QtWidgets.QWidget, Ui_IOUDevicePreferencesPageWid
self.uiEditIOUDevicePushButton.clicked.connect(self._iouDeviceEditSlot)
self.uiDeleteIOUDevicePushButton.clicked.connect(self._iouDeviceDeleteSlot)
self.uiIOUDevicesTreeWidget.itemSelectionChanged.connect(self._iouDeviceChangedSlot)
self.uiIOUDevicesTreeWidget.itemDoubleClicked.connect(self._iouDeviceEditSlot)
def _createSectionItem(self, name):
"""
@@ -87,7 +88,11 @@ class IOUDevicePreferencesPage(QtWidgets.QWidget, Ui_IOUDevicePreferencesPageWid
QtWidgets.QTreeWidgetItem(section_item, ["Template ID:", iou_device.get("template_id", "none")])
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", iou_device["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(iou_device["compute_id"]).name()])
compute_id = iou_device.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
# Compute doesn't exists
pass
@@ -210,7 +215,7 @@ class IOUDevicePreferencesPage(QtWidgets.QWidget, Ui_IOUDevicePreferencesPageWid
del self._iou_devices[key]
item.setText(0, iou_device["name"])
item.setData(0, QtCore.Qt.UserRole, new_key)
self._refreshInfo(dialog.settings)
self._refreshInfo(dialog.settings())
def _iouDeviceDeleteSlot(self):
"""

View File

@@ -32,7 +32,7 @@ IOU_DEVICE_SETTINGS = {
"default_name_format": "IOU{0}",
"usage": "",
"path": "",
"symbol": ":/symbols/multilayer_switch.svg",
"symbol": "multilayer_switch",
"category": Node.routers,
"startup_config": "",
"private_config": "",

View File

@@ -20,7 +20,6 @@ QEMU module implementation.
"""
from gns3.local_config import LocalConfig
from gns3.local_server_config import LocalServerConfig
from gns3.controller import Controller
from gns3.template_manager import TemplateManager
from gns3.template import Template
@@ -74,33 +73,11 @@ class Qemu(Module):
# save the settings
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
server_settings = {"enable_hardware_acceleration": self._settings["enable_hardware_acceleration"],
"require_hardware_acceleration": self._settings["require_hardware_acceleration"]}
LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
def getQemuBinariesFromServer(self, compute_id, callback, archs=None):
"""
Gets the QEMU binaries list from a server.
:param compute_id: server to send the request to
:param callback: callback for the reply from the server
:param archs: A list of architectures. Only binaries matching the specified architectures are returned.
"""
request_body = None
if archs is not None:
request_body = {"archs": archs}
Controller.instance().getCompute("/qemu/binaries", compute_id, callback, body=request_body)
def getQemuImgBinariesFromServer(self, compute_id, callback):
"""
Gets the QEMU-img binaries list from a server.
:param server: server to send the request to
:param callback: callback for the reply from the server
"""
Controller.instance().getCompute("/qemu/img-binaries", compute_id, callback)
# FIXME: handle server side config
# server_settings = {"enable_hardware_acceleration": self._settings["enable_hardware_acceleration"],
# "require_hardware_acceleration": self._settings["require_hardware_acceleration"]}
# LocalServerConfig.instance().saveSettings(self.__class__.__name__, server_settings)
def getQemuCapabilitiesFromServer(self, compute_id, callback):
"""
@@ -112,27 +89,44 @@ class Qemu(Module):
Controller.instance().getCompute("/qemu/capabilities", compute_id, callback)
def createDiskImage(self, compute_id, callback, options):
@staticmethod
def getQemuPlatforms():
"""
Create a disk image on the remote server
Returns all Qemu platforms
:param server: server to send the request to
:param callback: callback for the reply from the server
:param options: Options for the image creation
:return: list of Qemu platforms
"""
Controller.instance().postCompute("/qemu/img", compute_id, callback, body=options)
def updateDiskImage(self, compute_id, callback, options):
"""
Update a disk image on the remote server
:param server: server to send the request to
:param callback: callback for the reply from the server
:param options: Options for the image update
"""
Controller.instance().putCompute("/qemu/img", compute_id, callback, body=options)
return [
"aarch64",
"alpha",
"arm",
"cris",
"i386",
"lm32",
"m68k",
"microblaze",
"microblazeel",
"mips",
"mips64",
"mips64el",
"mipsel",
"moxie",
"or32",
"ppc",
"ppc64",
"ppcemb",
"s390x",
"sh4",
"sh4eb",
"sparc",
"sparc64",
"tricore",
"unicore32",
"x86_64",
"xtensa",
"xtensaeb"
]
@staticmethod
def getNodeClass(node_type, platform=None):

View File

@@ -16,13 +16,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Wizard for QEMU images.
Wizard for QEMU disk images.
"""
import os
from gns3.qt import QtCore, QtGui, QtWidgets, QFileDialog
from .. import Qemu
from gns3.qt import QtCore, QtGui, QtWidgets
from ..ui.qemu_image_wizard_ui import Ui_QemuImageWizard
@@ -32,19 +29,18 @@ class QemuImageWizard(QtWidgets.QWizard, Ui_QemuImageWizard):
Wizard to create a Qemu VM.
:param parent: parent widget
:param server: Server where the image should be created
:param node: node where the image should be created
:param filename: Default filename of image.
:param folder: Default folder for the image. If absent, defaults to Qemu's images folder.
:param size: Default size (in MiB) for the image.
"""
def __init__(self, parent, server, filename="disk", folder=None, size=30000):
def __init__(self, parent, node, filename="disk", size=30000):
super().__init__(parent)
self._server = server
self._node = node
self.setupUi(self)
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/icons/qemu.svg"))
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/symbols/qemu_guest.svg"))
# Initialize "constants"
self._mappings = {
@@ -57,45 +53,19 @@ class QemuImageWizard(QtWidgets.QWizard, Ui_QemuImageWizard):
}
# isComplete() overrides
self.uiSizeAndLocationWizardPage.isComplete = self._uiSizeAndLocationWizardPage_isComplete
self.uiBinaryWizardPage.isComplete = self._uiBinaryWizardPage_isComplete
self.uiNameAndSizeWizardPage.isComplete = self._uiNameAndSizeWizardPage_isComplete
self.uiFormatWizardPage.isComplete = self._uiFormatWizardPage_isComplete
# Signal connections
self.uiFormatRadios.buttonClicked.connect(self._formatChangedSlot)
self.uiLocationLineEdit.textChanged.connect(self._locationChangedSlot)
self.uiLocationBrowseToolButton.clicked.connect(self._browserSlot)
self.uiDiskFilenameLineEdit.textChanged.connect(self._filenameChangedSlot)
# Finish setup
self.page(self.pageIds()[-1]).validatePage = self._createDisk
# Default values
Qemu.instance().getQemuImgBinariesFromServer(self._server,
self._getQemuImgBinariesFromServerCallback)
self.uiLocationLineEdit.setText(filename)
self.uiDiskFilenameLineEdit.setText(filename)
self.uiSizeSpinBox.setValue(size)
self._formatChangedSlot(self.uiFormatQcow2Radio)
def _getQemuImgBinariesFromServerCallback(self, result, error=False, **kwargs):
"""
Callback for getQemuImgBinariesFromServer.
:param result: server response
:param error: indicates an error (boolean)
"""
if error:
QtWidgets.QMessageBox.critical(self, "Qemu-img binaries", "{}".format(result["message"]))
else:
self.uiBinaryComboBox.clear()
for qemu in result:
if qemu["version"]:
self.uiBinaryComboBox.addItem(
"{path} (v{version})".format(path=qemu["path"], version=qemu["version"]), qemu["path"]
)
else:
self.uiBinaryComboBox.addItem("{path}".format(path=qemu["path"]), qemu["path"])
self.uiBinaryWizardPage.completeChanged.emit()
def _getCreateDiskServerCallback(self, result, error=False, **kwargs):
"""
:param result: server response
@@ -105,45 +75,34 @@ class QemuImageWizard(QtWidgets.QWizard, Ui_QemuImageWizard):
if error:
QtWidgets.QMessageBox.critical(self, "Create disk", "{}".format(result["message"]))
def _uiSizeAndLocationWizardPage_isComplete(self):
return not "" == self.uiLocationLineEdit.text()
def _uiNameAndSizeWizardPage_isComplete(self):
def _uiBinaryWizardPage_isComplete(self):
return self.uiFormatRadios.checkedButton() is not None and self.uiBinaryComboBox.currentData() is not None
return not "" == self.uiDiskFilenameLineEdit.text()
def _locationChangedSlot(self, new_value):
self.uiSizeAndLocationWizardPage.completeChanged.emit()
def _uiFormatWizardPage_isComplete(self):
def _browserSlot(self):
path, name_filter = QFileDialog.getSaveFileName(
self,
'Image location',
self.uiLocationLineEdit.text(),
'{0} files (*{1});;All files (*)'.format(
self.uiFormatRadios.checkedButton().text(),
self._mappings[self.uiFormatRadios.checkedButton()][1]
),
options=QFileDialog.DontConfirmOverwrite
)
if path:
self.uiLocationLineEdit.setText(path)
return self.uiFormatRadios.checkedButton() is not None
def _filenameChangedSlot(self, new_value):
self.uiNameAndSizeWizardPage.completeChanged.emit()
def _formatChangedSlot(self, new_format):
dir, filename = os.path.split(self.uiLocationLineEdit.text())
filename = self.uiDiskFilenameLineEdit.text().strip()
try:
filename = filename[:filename.rindex('.')] + self._mappings[new_format][1]
except ValueError:
# The file has no extension; Just give it one
filename = filename + self._mappings[new_format][1]
self.uiLocationLineEdit.setText(os.path.join(dir, filename))
self.uiBinaryWizardPage.completeChanged.emit()
self.uiDiskFilenameLineEdit.setText(filename)
self.uiFormatWizardPage.completeChanged.emit()
def _createDisk(self):
selected_format = self.uiFormatRadios.checkedButton()
selected_format = self.uiFormatRadios.checkedButton()
disk_image_filename = self.uiDiskFilenameLineEdit.text().strip()
options = {}
options["path"] = self.uiLocationLineEdit.text()
options["qemu_img"] = self.uiBinaryComboBox.currentData()
options["format"] = self._mappings[selected_format][0]
options["size"] = self.uiSizeSpinBox.value()
@@ -214,11 +173,12 @@ class QemuImageWizard(QtWidgets.QWizard, Ui_QemuImageWizard):
}
options['subformat'] = two + size_mode_mappings[size_mode]
Qemu.instance().createDiskImage(self._server, self._getCreateDiskServerCallback, options)
self._node.createDiskImage(disk_image_filename, options, self._getCreateDiskServerCallback)
return True
def nextId(self):
if self.page(self.currentId()) == self.uiBinaryWizardPage:
if self.page(self.currentId()) == self.uiFormatWizardPage:
current_format = self.uiFormatRadios.checkedButton()
if not current_format:
return self.currentId()

View File

@@ -43,11 +43,10 @@ class QemuVMWizard(VMWithImagesWizard, Ui_QemuVMWizard):
def __init__(self, qemu_vms, parent):
super().__init__(qemu_vms, parent)
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/icons/qemu.svg"))
self.setPixmap(QtWidgets.QWizard.LogoPixmap, QtGui.QPixmap(":/symbols/qemu_guest.svg"))
# Mandatory fields
self.uiNameWizardPage.registerField("vm_name*", self.uiNameLineEdit)
self.uiDiskWizardPage.registerField("hda_disk_image*", self.uiHdaDiskImageLineEdit)
self.uiInitrdKernelImageWizardPage.registerField("initrd*", self.uiInitrdImageLineEdit)
self.uiInitrdKernelImageWizardPage.registerField("kernel_image*", self.uiKernelImageLineEdit)
@@ -56,31 +55,6 @@ class QemuVMWizard(VMWithImagesWizard, Ui_QemuVMWizard):
self.addImageSelector(self.uiLinuxExistingImageRadioButton, self.uiInitrdImageListComboBox, self.uiInitrdImageLineEdit, self.uiInitrdImageToolButton, QemuVMConfigurationPage.getDiskImage)
self.addImageSelector(self.uiLinuxExistingImageRadioButton, self.uiKernelImageListComboBox, self.uiKernelImageLineEdit, self.uiKernelImageToolButton, QemuVMConfigurationPage.getDiskImage)
def validateCurrentPage(self):
"""
Validates the server.
"""
if super().validateCurrentPage() is False:
return False
if self.currentPage() == self.uiNameWizardPage:
if self.uiLegacyASACheckBox.isChecked():
QtWidgets.QMessageBox.warning(self, "Legacy ASA VM", "Running ASA (with initrd/kernel) is not recommended and will not work on Windows 10, please use ASAv instead")
self.uiRamSpinBox.setValue(1024)
else:
self.uiRamSpinBox.setValue(256)
if self.currentPage() == self.uiBinaryMemoryWizardPage:
if not self.uiQemuListComboBox.count():
QtWidgets.QMessageBox.critical(self, "QEMU binaries", "Sorry, no QEMU binary has been found. Please make sure QEMU is installed before continuing")
return False
qemu_path = self.uiQemuListComboBox.itemData(self.uiQemuListComboBox.currentIndex())
if sys.platform.startswith("darwin") and "GNS3.app" in qemu_path:
QtWidgets.QMessageBox.warning(self, "Qemu binaries", "This version of qemu is obsolete and provided only for compatibility with old GNS3 versions.\nPlease use Qemu in the GNS3 VM for full Qemu support.")
return True
def initializePage(self, page_id):
super().initializePage(page_id)
@@ -90,53 +64,13 @@ class QemuVMWizard(VMWithImagesWizard, Ui_QemuVMWizard):
QtWidgets.QMessageBox.warning(self, "QEMU on Windows or Mac", "The recommended way to run QEMU on Windows and OSX is to use the GNS3 VM")
if self.page(page_id) in [self.uiDiskWizardPage, self.uiInitrdKernelImageWizardPage]:
self.loadImagesList("/qemu/images")
elif self.page(page_id) == self.uiBinaryMemoryWizardPage:
try:
Qemu.instance().getQemuBinariesFromServer(self._compute_id, self._getQemuBinariesFromServerCallback)
except ModuleError as e:
QtWidgets.QMessageBox.critical(self, "Qemu binaries", "Error while getting the QEMU binaries: {}".format(e))
def _getQemuBinariesFromServerCallback(self, result, error=False, **kwargs):
"""
Callback for getQemuBinariesFromServer.
:param result: server response
:param error: indicates an error (boolean)
"""
if error:
QtWidgets.QMessageBox.critical(self, "Qemu binaries", "{}".format(result["message"]))
else:
self.uiQemuListComboBox.clear()
for qemu in result:
if qemu["version"]:
self.uiQemuListComboBox.addItem("{path} (v{version})".format(path=qemu["path"], version=qemu["version"]), qemu["path"])
else:
self.uiQemuListComboBox.addItem("{path}".format(path=qemu["path"]), qemu["path"])
is_64bit = sys.maxsize > 2 ** 32
if ComputeManager.instance().localPlatform().startswith("win") and self.uiLocalRadioButton.isChecked():
if self.uiLegacyASACheckBox.isChecked():
search_string = r"qemu-0.13.0\qemu-system-i386w.exe"
elif is_64bit:
# default is qemu-system-x86_64w.exe on Windows 64-bit with a remote server
search_string = "x86_64w.exe"
else:
# default is qemu-system-i386w.exe on Windows 32-bit with a remote server
search_string = "i386w.exe"
elif ComputeManager.instance().localPlatform().startswith("darwin") and hasattr(sys, "frozen") and self.uiLocalRadioButton.isChecked():
search_string = "GNS3.app/Contents/MacOS/qemu/bin/qemu-system-x86_64"
elif is_64bit:
# default is qemu-system-x86_64 on other 64-bit platforms
search_string = "x86_64"
else:
# default is qemu-system-i386 on other platforms
search_string = "i386"
index = self.uiQemuListComboBox.findData(search_string, flags=QtCore.Qt.MatchEndsWith)
self.loadImagesList("qemu")
elif self.page(page_id) == self.uiPlatformMemoryWizardPage:
platforms = Qemu.getQemuPlatforms()
self.uiQemuPlatformComboBox.addItems(platforms)
index = self.uiQemuPlatformComboBox.findText("x86_64", flags=QtCore.Qt.MatchEndsWith)
if index != -1:
self.uiQemuListComboBox.setCurrentIndex(index)
self.uiQemuPlatformComboBox.setCurrentIndex(index)
def getSettings(self):
"""
@@ -146,38 +80,21 @@ class QemuVMWizard(VMWithImagesWizard, Ui_QemuVMWizard):
"""
console_type = self.uiQemuConsoleTypeComboBox.itemText(self.uiQemuConsoleTypeComboBox.currentIndex())
qemu_path = self.uiQemuListComboBox.itemData(self.uiQemuListComboBox.currentIndex())
qemu_platform = self.uiQemuPlatformComboBox.itemText(self.uiQemuPlatformComboBox.currentIndex())
settings = {
"name": self.uiNameLineEdit.text(),
"ram": self.uiRamSpinBox.value(),
"qemu_path": qemu_path,
"platform": qemu_platform,
"compute_id": self._compute_id,
"category": Node.end_devices,
"hda_disk_image": self.uiHdaDiskImageLineEdit.text(),
"console_type": console_type
}
if self.uiLegacyASACheckBox.isChecked():
# special settings for legacy ASA VM
settings["adapters"] = 4
settings["initrd"] = self.uiInitrdImageLineEdit.text()
settings["kernel_image"] = self.uiKernelImageLineEdit.text()
settings["kernel_command_line"] = "ide_generic.probe_mask=0x01 ide_core.chs=0.0:980,16,32 auto nousb console=ttyS0,9600 bigphysarea=65536 ide1=noprobe no-hlt -net nic"
settings["options"] = "-no-kvm -icount auto"
if not sys.platform.startswith("darwin"):
settings["cpu_throttling"] = 80 # limit to 80% CPU usage
settings["process_priority"] = "low"
settings["symbol"] = ":/symbols/asa.svg"
settings["category"] = Node.security_devices
if self.uiHdaDiskImageLineEdit.text().strip():
settings["hda_disk_image"] = self.uiHdaDiskImageLineEdit.text().strip()
if "options" not in settings:
settings["options"] = ""
if self._compute_id == "local" and (sys.platform.startswith("win") and qemu_path.endswith(r"qemu-0.11.0\qemu.exe")) or \
(sys.platform.startswith("darwin") and "GNS3.app" in qemu_path):
settings["options"] += " -vga none -vnc none"
settings["legacy_networking"] = True
else:
settings["options"] += " -nographic"
settings["options"] = settings["options"].strip()
return settings
@@ -189,8 +106,6 @@ class QemuVMWizard(VMWithImagesWizard, Ui_QemuVMWizard):
current_id = self.currentId()
if self.page(current_id) == self.uiDiskWizardPage:
if self.uiLegacyASACheckBox.isChecked():
return self.uiDiskWizardPage.nextId()
return -1
elif self.page(current_id) == self.uiInitrdKernelImageWizardPage:
return -1

View File

@@ -51,6 +51,8 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self._settings = None
self._custom_adapters = []
self.uiQemuPlatformComboBox.addItems(Qemu.getQemuPlatforms())
self.uiBootPriorityComboBox.addItem("HDD", "c")
self.uiBootPriorityComboBox.addItem("CD/DVD-ROM", "d")
self.uiBootPriorityComboBox.addItem("Network", "n")
@@ -78,7 +80,7 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiHdcDiskImageResizeToolButton.clicked.connect(self._hdcDiskImageResizeSlot)
self.uiHddDiskImageResizeToolButton.clicked.connect(self._hddDiskImageResizeSlot)
disk_interfaces = ["ide", "sata", "scsi", "sd", "mtd", "floppy", "pflash", "virtio", "none"]
disk_interfaces = ["ide", "sata", "nvme", "scsi", "sd", "mtd", "floppy", "pflash", "virtio", "none"]
self.uiHdaDiskInterfaceComboBox.addItems(disk_interfaces)
self.uiHdbDiskInterfaceComboBox.addItems(disk_interfaces)
self.uiHdcDiskInterfaceComboBox.addItems(disk_interfaces)
@@ -88,8 +90,8 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiInitrdToolButton.clicked.connect(self._initrdBrowserSlot)
self.uiKernelImageToolButton.clicked.connect(self._kernelImageBrowserSlot)
self.uiActivateCPUThrottlingCheckBox.stateChanged.connect(self._cpuThrottlingChangedSlot)
self.uiLegacyNetworkingCheckBox.stateChanged.connect(self._legacyNetworkingChangedSlot)
self.uiCustomAdaptersConfigurationPushButton.clicked.connect(self._customAdaptersConfigurationSlot)
self.uiCreateConfigDiskCheckBox.stateChanged.connect(self._createConfigDiskChangedSlot)
# add the categories
for name, category in Node.defaultCategories().items():
@@ -99,8 +101,13 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
for name, option_name in Node.onCloseOptions().items():
self.uiOnCloseComboBox.addItem(name, option_name)
self._legacy_devices = ("e1000", "i82551", "i82557b", "i82559er", "ne2k_pci", "pcnet", "rtl8139", "virtio")
# Supported NIC models: e1000, e1000-82544gc, e1000-82545em, e1000e, i82550, i82551, i82557a, i82557b, i82557c, i82558a
# i82558b, i82559a, i82559b, i82559c, i82559er, i82562, i82801, ne2k_pci, pcnet, rocker, rtl8139, virtio-net-pci, vmxnet3
# This list can be retrieved using "qemu-system-x86_64 -nic model=?" or "qemu-system-x86_64 -device help"
self._qemu_network_devices = OrderedDict([("e1000", "Intel Gigabit Ethernet"),
("e1000-82544gc", "Intel 82544GC Gigabit Ethernet"),
("e1000-82545em", "Intel 82545EM Gigabit Ethernet"),
("e1000e", "Intel PCIe Gigabit Ethernet"),
("i82550", "Intel i82550 Ethernet"),
("i82551", "Intel i82551 Ethernet"),
("i82557a", "Intel i82557A Ethernet"),
@@ -116,8 +123,8 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
("i82801", "Intel i82801 Ethernet"),
("ne2k_pci", "NE2000 Ethernet"),
("pcnet", "AMD PCNet Ethernet"),
("rocker", "Rocker L2 switch device"),
("rtl8139", "Realtek 8139 Ethernet"),
("virtio", "Legacy paravirtualized Network I/O"),
("virtio-net-pci", "Paravirtualized Network I/O"),
("vmxnet3", "VMWare Paravirtualized Ethernet v3")])
@@ -136,17 +143,14 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiSymbolLineEdit.setText(new_symbol_path)
self.uiSymbolLineEdit.setToolTip('<img src="{}"/>'.format(new_symbol_path))
def _refreshQemuNetworkDevices(self, legacy_networking=False):
def _refreshQemuNetworkDevices(self,):
"""
Refreshes the Qemu network device list.
:param legacy_networking: True if legacy networking is enabled.
"""
self.uiAdapterTypesComboBox.clear()
for device_name, device_description in self._qemu_network_devices.items():
if legacy_networking and device_name not in self._legacy_devices:
continue
self.uiAdapterTypesComboBox.addItem("{} ({})".format(device_description, device_name), device_name)
@staticmethod
@@ -233,24 +237,64 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiCdromImageLineEdit.setText(path)
def _hdaDiskImageCreateSlot(self):
create_dialog = QemuImageWizard(self, self._compute_id, self.uiNameLineEdit.text() + '-hda')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdaDiskImageLineEdit.setText(create_dialog.uiLocationLineEdit.text())
if self._node:
create_dialog = QemuImageWizard(self, self._node, self.uiNameLineEdit.text() + '-hda')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdaDiskImageLineEdit.setText(create_dialog.uiDiskFilenameLineEdit.text())
def _hdbDiskImageCreateSlot(self):
create_dialog = QemuImageWizard(self, self._compute_id, self.uiNameLineEdit.text() + '-hdb')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdbDiskImageLineEdit.setText(create_dialog.uiLocationLineEdit.text())
if self._node:
create_dialog = QemuImageWizard(self, self._node, self.uiNameLineEdit.text() + '-hdb')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdbDiskImageLineEdit.setText(create_dialog.uiDiskFilenameLineEdit.text())
def _hdcDiskImageCreateSlot(self):
create_dialog = QemuImageWizard(self, self._compute_id, self.uiNameLineEdit.text() + '-hdc')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdcDiskImageLineEdit.setText(create_dialog.uiLocationLineEdit.text())
if self._node:
create_dialog = QemuImageWizard(self, self._node, self.uiNameLineEdit.text() + '-hdc')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHdcDiskImageLineEdit.setText(create_dialog.uiDiskFilenameLineEdit.text())
def _hddDiskImageCreateSlot(self):
create_dialog = QemuImageWizard(self, self._compute_id, self.uiNameLineEdit.text() + '-hdd')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHddDiskImageLineEdit.setText(create_dialog.uiLocationLineEdit.text())
if self._node:
create_dialog = QemuImageWizard(self, self._node, self.uiNameLineEdit.text() + '-hdd')
if QtWidgets.QDialog.Accepted == create_dialog.exec_():
self.uiHddDiskImageLineEdit.setText(create_dialog.uiDiskFilenameLineEdit.text())
def _hdaDiskImageResizeSlot(self):
disk_image_filename = self.uiHdaDiskImageLineEdit.text().strip()
if disk_image_filename:
size, ok = QtWidgets.QInputDialog.getInt(self, "HDA disk size", "Increase hda disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage(disk_image_filename, size, self._resizeDiskImageCallback)
def _hdbDiskImageResizeSlot(self):
disk_image_filename = self.uiHdbDiskImageLineEdit.text()
if disk_image_filename:
size, ok = QtWidgets.QInputDialog.getInt(self, "HDB disk size", "Increase hdb disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage(disk_image_filename, size, self._resizeDiskImageCallback)
def _hdcDiskImageResizeSlot(self):
disk_image_filename = self.uiHdcDiskImageLineEdit.text()
if disk_image_filename:
size, ok = QtWidgets.QInputDialog.getInt(self, "HDC disk size", "Increase hdc disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage(disk_image_filename, size, self._resizeDiskImageCallback)
def _hddDiskImageResizeSlot(self):
disk_image_filename = self.uiHddDiskImageLineEdit.text()
if disk_image_filename:
size, ok = QtWidgets.QInputDialog.getInt(self, "HDD disk size", "Increase hdd disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage(disk_image_filename, size, self._resizeDiskImageCallback)
def _resizeDiskImageCallback(self, result, error=False, **kwargs):
"""
@@ -265,25 +309,6 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
else:
QtWidgets.QMessageBox.information(self, "Disk image", "The disk has been resized")
def _hdaDiskImageResizeSlot(self):
size, ok = QtWidgets.QInputDialog.getInt(self, "HDA disk size", "Increase hda disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage("hda", size, self._resizeDiskImageCallback)
def _hdbDiskImageResizeSlot(self):
size, ok = QtWidgets.QInputDialog.getInt(self, "HDB disk size", "Increase hdb disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage("hdb", size, self._resizeDiskImageCallback)
def _hdcDiskImageResizeSlot(self):
size, ok = QtWidgets.QInputDialog.getInt(self, "HDC disk size", "Increase hdc disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage("hdc", size, self._resizeDiskImageCallback)
def _hddDiskImageResizeSlot(self):
size, ok = QtWidgets.QInputDialog.getInt(self, "HDD disk size", "Increase hdd disk size in MB:", 10000, 1, 1000000000, 1000)
if ok and self._node:
self._node.resizeDiskImage("hdd", size, self._resizeDiskImageCallback)
def _initrdBrowserSlot(self):
"""
@@ -305,40 +330,6 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiKernelImageLineEdit.clear()
self.uiKernelImageLineEdit.setText(path)
def _getQemuBinariesFromServerCallback(self, result, error=False, qemu_path=None, **kwargs):
"""
Callback for getQemuBinariesFromServer.
:param result: server response
:param error: indicates an error (boolean)
"""
if sip_is_deleted(self.uiQemuListComboBox) or sip_is_deleted(self):
return
if error:
QtWidgets.QMessageBox.critical(self, "Qemu binaries", "{}".format(result["message"]))
else:
self.uiQemuListComboBox.clear()
for qemu in result:
if qemu["version"]:
self.uiQemuListComboBox.addItem("{path} (v{version})".format(path=qemu["path"], version=qemu["version"]), qemu["path"])
else:
self.uiQemuListComboBox.addItem("{path}".format(path=qemu["path"]), qemu["path"])
if qemu_path and "/" not in qemu_path and "\\" not in qemu_path:
self.uiQemuListComboBox.addItem("{path}".format(path=qemu_path), qemu_path)
index = self.uiQemuListComboBox.findData("{path}".format(path=qemu_path))
if index != -1:
self.uiQemuListComboBox.setCurrentIndex(index)
else:
index = self.uiQemuListComboBox.findData("{path}".format(path=os.path.basename(qemu_path)), flags=QtCore.Qt.MatchEndsWith)
self.uiQemuListComboBox.setCurrentIndex(index)
if index == -1:
QtWidgets.QMessageBox.warning(self, "Qemu","Could not find '{}' in the Qemu binaries list, please select a new binary".format(qemu_path))
else:
QtWidgets.QMessageBox.warning(self, "Qemu","Could not find '{}' in the Qemu binaries list, an alternative path has been selected".format(qemu_path))
def _cpuThrottlingChangedSlot(self, state):
"""
@@ -350,15 +341,18 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
else:
self.uiCPUThrottlingSpinBox.setEnabled(False)
def _legacyNetworkingChangedSlot(self, state):
def _createConfigDiskChangedSlot(self, state):
"""
Slot to enable or not legacy networking.
Slot to allow or not HDD disk to be configured based on the state of the config disk option.
"""
_translate = QtCore.QCoreApplication.translate
if state:
self._refreshQemuNetworkDevices(legacy_networking=True)
self.uiHddDiskImageLabel.setText(_translate("QemuVMConfigPageWidget", "Startup-cfg:"))
else:
self._refreshQemuNetworkDevices()
self.uiHddDiskImageLabel.setText(_translate("QemuVMConfigPageWidget", "Disk image:"))
self.uiHddDiskImageCreateToolButton.setEnabled(not state)
self.uiHddDiskImageResizeToolButton.setEnabled(not state)
def _customAdaptersConfigurationSlot(self):
"""
@@ -395,7 +389,8 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
QtWidgets.QMessageBox.critical(self, "Invalid format", "Invalid port name format")
return
dialog = CustomAdaptersConfigurationDialog(ports, self._custom_adapters, default_adapter, self._qemu_network_devices, base_mac_address, parent=self)
network_devices = self._qemu_network_devices.copy()
dialog = CustomAdaptersConfigurationDialog(ports, self._custom_adapters, default_adapter, network_devices, base_mac_address, parent=self)
dialog.show()
dialog.exec_()
@@ -416,12 +411,6 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self._compute_id = settings["compute_id"]
self._node = None
if self._compute_id is None:
QtWidgets.QMessageBox.warning(self, "Qemu", "Server {} is not running, cannot retrieve the QEMU binaries list".format(settings["compute_id"]))
else:
callback = qpartial(self._getQemuBinariesFromServerCallback, qemu_path=settings["qemu_path"])
Qemu.instance().getQemuBinariesFromServer(self._compute_id, callback)
if not group:
# set the device name
self.uiNameLineEdit.setText(settings["name"])
@@ -439,6 +428,7 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiHdbDiskInterfaceComboBox.setCurrentIndex(self.uiHdbDiskInterfaceComboBox.findText(settings["hdb_disk_interface"]))
self.uiHdcDiskInterfaceComboBox.setCurrentIndex(self.uiHdcDiskInterfaceComboBox.findText(settings["hdc_disk_interface"]))
self.uiHddDiskInterfaceComboBox.setCurrentIndex(self.uiHddDiskInterfaceComboBox.findText(settings["hdd_disk_interface"]))
self.uiCreateConfigDiskCheckBox.setChecked(settings["create_config_disk"])
self.uiCdromImageLineEdit.setText(settings["cdrom_image"])
self.uiBiosImageLineEdit.setText(settings["bios_image"])
self.uiInitrdLineEdit.setText(settings["initrd"])
@@ -477,6 +467,11 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiPortSegmentSizeSpinBox.setValue(settings["port_segment_size"])
self.uiFirstPortNameLineEdit.setText(settings["first_port_name"])
self.uiHdaDiskImageCreateToolButton.hide()
self.uiHdbDiskImageCreateToolButton.hide()
self.uiHdcDiskImageCreateToolButton.hide()
self.uiHddDiskImageCreateToolButton.hide()
self.uiHdaDiskImageResizeToolButton.hide()
self.uiHdbDiskImageResizeToolButton.hide()
self.uiHdcDiskImageResizeToolButton.hide()
@@ -497,6 +492,10 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
self.uiFirstPortNameLabel.hide()
self.uiFirstPortNameLineEdit.hide()
index = self.uiQemuPlatformComboBox.findText(settings["platform"])
if index != -1:
self.uiQemuPlatformComboBox.setCurrentIndex(index)
index = self.uiBootPriorityComboBox.findData(settings["boot_priority"])
if index != -1:
self.uiBootPriorityComboBox.setCurrentIndex(index)
@@ -505,12 +504,15 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
if index != -1:
self.uiConsoleTypeComboBox.setCurrentIndex(index)
index = self.uiAuxTypeComboBox.findText(settings["aux_type"])
if index != -1:
self.uiAuxTypeComboBox.setCurrentIndex(index)
self.uiConsoleAutoStartCheckBox.setChecked(settings["console_auto_start"])
self.uiKernelCommandLineEdit.setText(settings["kernel_command_line"])
self.uiAdaptersSpinBox.setValue(settings["adapters"])
self._custom_adapters = settings["custom_adapters"].copy()
self.uiLegacyNetworkingCheckBox.setChecked(settings["legacy_networking"])
self.uiReplicateNetworkConnectionStateCheckBox.setChecked(settings["replicate_network_connection_state"])
# load the MAC address setting
self.uiMacAddrLineEdit.setInputMask("HH:HH:HH:HH:HH:HH;_")
@@ -573,6 +575,7 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
settings["hdb_disk_interface"] = self.uiHdbDiskInterfaceComboBox.currentText()
settings["hdc_disk_interface"] = self.uiHdcDiskInterfaceComboBox.currentText()
settings["hdd_disk_interface"] = self.uiHddDiskInterfaceComboBox.currentText()
settings["create_config_disk"] = self.uiCreateConfigDiskCheckBox.isChecked()
settings["cdrom_image"] = self.uiCdromImageLineEdit.text().strip()
settings["bios_image"] = self.uiBiosImageLineEdit.text().strip()
settings["initrd"] = self.uiInitrdLineEdit.text().strip()
@@ -618,17 +621,11 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
settings["port_segment_size"] = port_segment_size
settings["first_port_name"] = first_port_name
if self.uiQemuListComboBox.currentIndex() != -1:
qemu_path = self.uiQemuListComboBox.itemData(self.uiQemuListComboBox.currentIndex())
settings["qemu_path"] = qemu_path
else:
QtWidgets.QMessageBox.critical(self, "Qemu binary", "Please select a Qemu binary")
if node:
raise ConfigurationError()
settings["platform"] = self.uiQemuPlatformComboBox.itemText(self.uiQemuPlatformComboBox.currentIndex())
settings["boot_priority"] = self.uiBootPriorityComboBox.itemData(self.uiBootPriorityComboBox.currentIndex())
settings["console_type"] = self.uiConsoleTypeComboBox.currentText().lower()
settings["console_auto_start"] = self.uiConsoleAutoStartCheckBox.isChecked()
settings["aux_type"] = self.uiAuxTypeComboBox.currentText().lower()
settings["adapter_type"] = self.uiAdapterTypesComboBox.itemData(self.uiAdapterTypesComboBox.currentIndex())
settings["kernel_command_line"] = self.uiKernelCommandLineEdit.text()
@@ -642,6 +639,7 @@ class QemuVMConfigurationPage(QtWidgets.QWidget, Ui_QemuVMConfigPageWidget):
raise ConfigurationError()
settings["adapters"] = adapters
settings["replicate_network_connection_state"] = self.uiReplicateNetworkConnectionStateCheckBox.isChecked()
settings["custom_adapters"] = self._custom_adapters.copy()
settings["on_close"] = self.uiOnCloseComboBox.itemData(self.uiOnCloseComboBox.currentIndex())
settings["cpus"] = self.uiCPUSpinBox.value()

View File

@@ -54,6 +54,7 @@ class QemuVMPreferencesPage(QtWidgets.QWidget, Ui_QemuVMPreferencesPageWidget):
self.uiEditQemuVMPushButton.clicked.connect(self._qemuVMEditSlot)
self.uiDeleteQemuVMPushButton.clicked.connect(self._qemuVMDeleteSlot)
self.uiQemuVMsTreeWidget.itemSelectionChanged.connect(self._qemuVMChangedSlot)
self.uiQemuVMsTreeWidget.itemDoubleClicked.connect(self._qemuVMEditSlot)
def _createSectionItem(self, name):
"""
@@ -83,18 +84,21 @@ class QemuVMPreferencesPage(QtWidgets.QWidget, Ui_QemuVMPreferencesPageWidget):
if qemu_vm["linked_clone"]:
QtWidgets.QTreeWidgetItem(section_item, ["Default name format:", qemu_vm["default_name_format"]])
try:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(qemu_vm["compute_id"]).name()])
compute_id = qemu_vm.get("compute_id")
if compute_id:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", ComputeManager.instance().getCompute(compute_id).name()])
else:
QtWidgets.QTreeWidgetItem(section_item, ["Server:", "Dynamically allocated by the controller"])
except KeyError:
pass
QtWidgets.QTreeWidgetItem(section_item, ["QEMU platform:", os.path.basename(qemu_vm["platform"])])
QtWidgets.QTreeWidgetItem(section_item, ["Console type:", qemu_vm["console_type"]])
QtWidgets.QTreeWidgetItem(section_item, ["Auto start console:", "{}".format(qemu_vm["console_auto_start"])])
QtWidgets.QTreeWidgetItem(section_item, ["Auxiliary console type:", qemu_vm["aux_type"]])
QtWidgets.QTreeWidgetItem(section_item, ["CPUs:", str(qemu_vm["cpus"])])
QtWidgets.QTreeWidgetItem(section_item, ["Memory:", "{} MB".format(qemu_vm["ram"])])
QtWidgets.QTreeWidgetItem(section_item, ["Linked base VM:", "{}".format(qemu_vm["linked_clone"])])
if qemu_vm["qemu_path"]:
QtWidgets.QTreeWidgetItem(section_item, ["QEMU binary:", os.path.basename(qemu_vm["qemu_path"])])
# fill out the Hard disks section
if qemu_vm["hda_disk_image"] or qemu_vm["hdb_disk_image"] or qemu_vm["hdc_disk_image"] or qemu_vm["hdd_disk_image"]:
section_item = self._createSectionItem("Hard disks")

View File

@@ -19,6 +19,8 @@
QEMU VM implementation.
"""
import re
from gns3.node import Node
from .settings import QEMU_VM_SETTINGS
@@ -43,7 +45,6 @@ class QemuVM(Node):
self._linked_clone = True
qemu_vm_settings = {"usage": "",
"qemu_path": "",
"hda_disk_image": "",
"hdb_disk_image": "",
"hdc_disk_image": "",
@@ -66,11 +67,13 @@ class QemuVM(Node):
"cpus": QEMU_VM_SETTINGS["cpus"],
"console_type": QEMU_VM_SETTINGS["console_type"],
"console_auto_start": QEMU_VM_SETTINGS["console_auto_start"],
"aux_type": QEMU_VM_SETTINGS["aux_type"],
"adapters": QEMU_VM_SETTINGS["adapters"],
"custom_adapters": QEMU_VM_SETTINGS["custom_adapters"],
"adapter_type": QEMU_VM_SETTINGS["adapter_type"],
"mac_address": QEMU_VM_SETTINGS["mac_address"],
"legacy_networking": QEMU_VM_SETTINGS["legacy_networking"],
"replicate_network_connection_state": QEMU_VM_SETTINGS["replicate_network_connection_state"],
"create_config_disk": QEMU_VM_SETTINGS["create_config_disk"],
"platform": QEMU_VM_SETTINGS["platform"],
"on_close": QEMU_VM_SETTINGS["on_close"],
"cpu_throttling": QEMU_VM_SETTINGS["cpu_throttling"],
@@ -86,16 +89,24 @@ class QemuVM(Node):
self.settings().update(qemu_vm_settings)
def resizeDiskImage(self, drive_name, size, callback):
def createDiskImage(self, disk_name, options, callback):
"""
Resize a disk image allocated to the VM.
Create a disk image attached to the VM.
:param callback: callback for the reply from the server
"""
params = {"drive_name": drive_name,
"extend": size}
self.post("/resize_disk", callback, body=params)
self.post(f"/qemu/disk_image/{disk_name}", callback, body=options)
def resizeDiskImage(self, disk_name, size, callback):
"""
Resize a disk image attached to the VM.
:param callback: callback for the reply from the server
"""
params = {"extend": size}
self.put(f"/qemu/disk_image/{disk_name}", callback, body=params)
def info(self):
"""
@@ -109,6 +120,7 @@ class QemuVM(Node):
Local ID is {id} and server ID is {node_id}
Number of processors is {cpus} and amount of memory is {ram}MB
Console is on port {console} and type is {console_type}
Auxiliary console is on port {aux} and type is {aux_type}
""".format(name=self.name(),
id=self.id(),
node_id=self._node_id,
@@ -118,7 +130,9 @@ class QemuVM(Node):
cpus=self._settings["cpus"],
ram=self._settings["ram"],
console=self._settings["console"],
console_type=self._settings["console_type"])
console_type=self._settings["console_type"],
aux=self._settings["aux"],
aux_type=self._settings["aux_type"])
port_info = ""
for port in self._ports:
@@ -133,6 +147,33 @@ class QemuVM(Node):
usage = "\n" + self._settings.get("usage")
return info + port_info + usage
def configFiles(self):
"""
Name of the configuration files
"""
if self._settings.get("create_config_disk"):
return ["config.zip"]
return None
def configTextFiles(self):
"""
Name of the configuration files, which are plain text files
:returns: List of configuration files, False if no files
"""
return None
def auxConsole(self):
"""
Returns the console port for this Docker VM instance.
:returns: port (integer)
"""
return self._settings["aux"]
def configPage(self):
"""
Returns the configuration page widget to be used by the node properties dialog.

View File

@@ -30,34 +30,35 @@ QEMU_VM_SETTINGS = {
"name": "",
"default_name_format": "{name}-{0}",
"usage": "",
"symbol": ":/symbols/qemu_guest.svg",
"symbol": "qemu_guest",
"category": Node.end_devices,
"port_name_format": "Ethernet{0}",
"port_segment_size": 0,
"first_port_name": "",
"custom_adapters": [],
"qemu_path": "",
"hda_disk_image": "",
"hdb_disk_image": "",
"hdc_disk_image": "",
"hdd_disk_image": "",
"hda_disk_interface": "ide",
"hdb_disk_interface": "ide",
"hdc_disk_interface": "ide",
"hdd_disk_interface": "ide",
"hda_disk_interface": "none",
"hdb_disk_interface": "none",
"hdc_disk_interface": "none",
"hdd_disk_interface": "none",
"cdrom_image": "",
"bios_image": "",
"boot_priority": "c",
"console_type": "telnet",
"console_auto_start": False,
"aux_type": "none",
"ram": 256,
"cpus": 1,
"adapters": 1,
"adapter_type": "e1000",
"mac_address": "",
"legacy_networking": False,
"replicate_network_connection_state": True,
"create_config_disk": False,
"on_close": "power_off",
"platform": "",
"platform": "x86_64",
"cpu_throttling": 0,
"process_priority": "normal",
"options": "",

View File

@@ -6,12 +6,12 @@
<rect>
<x>0</x>
<y>0</y>
<width>535</width>
<height>369</height>
<width>493</width>
<height>314</height>
</rect>
</property>
<property name="windowTitle">
<string>Qemu image creator</string>
<string>Qemu disk image creator</string>
</property>
<property name="modal">
<bool>true</bool>
@@ -19,39 +19,22 @@
<property name="wizardStyle">
<enum>QWizard::ModernStyle</enum>
</property>
<widget class="QWizardPage" name="uiBinaryWizardPage">
<widget class="QWizardPage" name="uiFormatWizardPage">
<property name="title">
<string>Binary and format</string>
<string>Disk image format</string>
</property>
<property name="subTitle">
<string>Please select a qemu-img binary, and the format for your new image.</string>
<string>Please select the disk image format</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLabel" name="uiBinaryLabel">
<widget class="QLabel" name="uiFormatLabel">
<property name="text">
<string>Qemu-img binary:</string>
<string>Disk image format:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="uiBinaryComboBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="uiFormatLabel">
<property name="text">
<string>Image format:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QRadioButton" name="uiFormatQcow2Radio">
@@ -682,31 +665,20 @@ Free space will be zero filled.</string>
</item>
</layout>
</widget>
<widget class="QWizardPage" name="uiSizeAndLocationWizardPage">
<widget class="QWizardPage" name="uiNameAndSizeWizardPage">
<property name="title">
<string>Size and location</string>
</property>
<layout class="QGridLayout" name="gridLayout_4">
<item row="0" column="0">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="uiLocationLabel">
<property name="text">
<string>File location:</string>
<string>Disk filename:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="uiLocationLineEdit"/>
</item>
<item>
<widget class="QToolButton" name="uiLocationBrowseToolButton">
<property name="text">
<string>Browse</string>
</property>
</widget>
</item>
</layout>
<item row="0" column="2">
<widget class="QLineEdit" name="uiDiskFilenameLineEdit"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="uiSizeLabel">
@@ -715,34 +687,30 @@ Free space will be zero filled.</string>
</property>
</widget>
</item>
<item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_7">
<item>
<widget class="QSpinBox" name="uiSizeSpinBox">
<property name="buttonSymbols">
<enum>QAbstractSpinBox::UpDownArrows</enum>
</property>
<property name="suffix">
<string> MiB</string>
</property>
<property name="minimum">
<number>0</number>
</property>
<property name="maximum">
<number>2000000</number>
</property>
<property name="singleStep">
<number>1000</number>
</property>
<property name="value">
<number>30000</number>
</property>
<property name="showGroupSeparator" stdset="0">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
<item row="1" column="2">
<widget class="QSpinBox" name="uiSizeSpinBox">
<property name="buttonSymbols">
<enum>QAbstractSpinBox::UpDownArrows</enum>
</property>
<property name="showGroupSeparator" stdset="0">
<bool>true</bool>
</property>
<property name="suffix">
<string> MiB</string>
</property>
<property name="minimum">
<number>0</number>
</property>
<property name="maximum">
<number>2000000</number>
</property>
<property name="singleStep">
<number>1000</number>
</property>
<property name="value">
<number>30000</number>
</property>
</widget>
</item>
</layout>
</widget>
@@ -783,11 +751,11 @@ Free space will be zero filled.</string>
</connection>
</connections>
<buttongroups>
<buttongroup name="uiQcow2PreallocationRadios"/>
<buttongroup name="uiVmdkAdapterRadios"/>
<buttongroup name="uiFormatRadios"/>
<buttongroup name="uiVdiSizeModeRadios"/>
<buttongroup name="uiVmdkSizeModeRadios"/>
<buttongroup name="uiFormatRadios"/>
<buttongroup name="uiVhdSizeModeRadios"/>
<buttongroup name="uiQcow2PreallocationRadios"/>
</buttongroups>
</ui>

Some files were not shown because too many files have changed in this diff Show More