2019-01-14 09:09:06 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Copyright (C) 2019 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/>.
|
|
|
|
|
2022-11-08 14:50:59 +00:00
|
|
|
import sys
|
2019-01-14 09:09:06 +00:00
|
|
|
import os
|
|
|
|
import json
|
|
|
|
import asyncio
|
2021-10-10 07:05:11 +00:00
|
|
|
import aiofiles
|
2022-11-07 12:12:03 +00:00
|
|
|
import shutil
|
2021-10-10 07:05:11 +00:00
|
|
|
|
2022-12-30 01:15:40 +00:00
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
from typing import Tuple, List
|
2021-10-10 07:05:11 +00:00
|
|
|
from aiohttp.client_exceptions import ClientError
|
2019-01-14 09:09:06 +00:00
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
from uuid import UUID
|
|
|
|
from pydantic import ValidationError
|
|
|
|
|
2019-01-14 09:09:06 +00:00
|
|
|
from .appliance import Appliance
|
|
|
|
from ..config import Config
|
|
|
|
from ..utils.asyncio import locking
|
2020-10-22 05:49:44 +00:00
|
|
|
from ..utils.http_client import HTTPClient
|
2021-10-18 07:34:30 +00:00
|
|
|
from .controller_error import ControllerBadRequestError, ControllerNotFoundError, ControllerError
|
2021-10-10 07:05:11 +00:00
|
|
|
from .appliance_to_template import ApplianceToTemplate
|
|
|
|
from ..utils.images import InvalidImageError, write_image, md5sum
|
|
|
|
from ..utils.asyncio import wait_run_in_executor
|
2019-01-14 09:09:06 +00:00
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
from gns3server import schemas
|
|
|
|
from gns3server.utils.images import default_images_directory
|
|
|
|
from gns3server.db.repositories.images import ImagesRepository
|
|
|
|
from gns3server.db.repositories.templates import TemplatesRepository
|
|
|
|
from gns3server.services.templates import TemplatesService
|
|
|
|
from gns3server.db.repositories.rbac import RbacRepository
|
|
|
|
|
2019-01-14 09:09:06 +00:00
|
|
|
import logging
|
2021-04-13 09:16:50 +00:00
|
|
|
|
2019-01-14 09:09:06 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class ApplianceManager:
|
|
|
|
"""
|
|
|
|
Manages appliances
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
|
|
self._appliances = {}
|
|
|
|
self._appliances_etag = None
|
|
|
|
|
|
|
|
@property
|
2021-10-18 07:34:30 +00:00
|
|
|
def appliances_etag(self) -> str:
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
|
|
|
:returns: ETag for downloaded appliances
|
|
|
|
"""
|
|
|
|
|
|
|
|
return self._appliances_etag
|
|
|
|
|
|
|
|
@appliances_etag.setter
|
|
|
|
def appliances_etag(self, etag):
|
|
|
|
"""
|
|
|
|
:param etag: ETag for downloaded appliances
|
|
|
|
"""
|
|
|
|
|
|
|
|
self._appliances_etag = etag
|
|
|
|
|
|
|
|
@property
|
2021-10-18 07:34:30 +00:00
|
|
|
def appliances(self) -> dict:
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
|
|
|
:returns: The dictionary of appliances managed by GNS3
|
|
|
|
"""
|
|
|
|
|
|
|
|
return self._appliances
|
|
|
|
|
2022-11-09 12:30:28 +00:00
|
|
|
def _custom_appliances_path(self) -> str:
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
2022-11-07 12:12:03 +00:00
|
|
|
Get the custom appliance storage directory
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
|
|
|
|
2021-04-12 07:32:23 +00:00
|
|
|
server_config = Config.instance().settings.Server
|
|
|
|
appliances_path = os.path.expanduser(server_config.appliances_path)
|
2019-01-14 09:09:06 +00:00
|
|
|
os.makedirs(appliances_path, exist_ok=True)
|
|
|
|
return appliances_path
|
|
|
|
|
2023-01-01 09:49:00 +00:00
|
|
|
def _builtin_appliances_path(self, delete_first=False):
|
2022-11-07 12:12:03 +00:00
|
|
|
"""
|
|
|
|
Get the built-in appliance storage directory
|
|
|
|
"""
|
|
|
|
|
|
|
|
config = Config.instance()
|
|
|
|
appliances_dir = os.path.join(config.config_dir, "appliances")
|
2023-01-01 09:49:00 +00:00
|
|
|
if delete_first:
|
|
|
|
shutil.rmtree(appliances_dir, ignore_errors=True)
|
2022-11-07 12:12:03 +00:00
|
|
|
os.makedirs(appliances_dir, exist_ok=True)
|
|
|
|
return appliances_dir
|
|
|
|
|
|
|
|
def install_builtin_appliances(self):
|
|
|
|
"""
|
|
|
|
At startup we copy the built-in appliances files.
|
|
|
|
"""
|
|
|
|
|
2023-01-01 09:49:00 +00:00
|
|
|
dst_path = self._builtin_appliances_path(delete_first=True)
|
2023-01-01 07:57:41 +00:00
|
|
|
log.info(f"Installing built-in appliances in '{dst_path}'")
|
2023-05-07 13:57:44 +00:00
|
|
|
from . import Controller
|
2022-11-07 12:12:03 +00:00
|
|
|
try:
|
2023-05-07 13:57:44 +00:00
|
|
|
Controller.instance().install_resource_files(dst_path, "appliances")
|
2022-11-07 12:12:03 +00:00
|
|
|
except OSError as e:
|
|
|
|
log.error(f"Could not install built-in appliance files to {dst_path}: {e}")
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
def _find_appliances_from_image_checksum(self, image_checksum: str) -> List[Tuple[Appliance, str]]:
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
2021-10-18 07:34:30 +00:00
|
|
|
Find appliances that matches an image checksum.
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
2021-08-11 07:28:23 +00:00
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
appliances = []
|
2021-08-11 07:28:23 +00:00
|
|
|
for appliance in self._appliances.values():
|
|
|
|
if appliance.images:
|
|
|
|
for image in appliance.images:
|
2021-10-10 07:05:11 +00:00
|
|
|
if image.get("md5sum") == image_checksum:
|
2021-10-18 07:34:30 +00:00
|
|
|
appliances.append((appliance, image.get("version")))
|
|
|
|
return appliances
|
|
|
|
|
|
|
|
async def _download_image(
|
|
|
|
self,
|
|
|
|
image_dir: str,
|
|
|
|
image_name: str,
|
|
|
|
image_type: str,
|
|
|
|
image_url: str,
|
|
|
|
images_repo: ImagesRepository
|
|
|
|
) -> None:
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
|
|
|
Download an image.
|
|
|
|
"""
|
|
|
|
|
|
|
|
log.info(f"Downloading image '{image_name}' from '{image_url}'")
|
|
|
|
image_path = os.path.join(image_dir, image_name)
|
|
|
|
try:
|
|
|
|
async with HTTPClient.get(image_url) as response:
|
|
|
|
if response.status != 200:
|
|
|
|
raise ControllerError(f"Could not download '{image_name}' due to HTTP error code {response.status}")
|
2022-07-22 10:39:52 +00:00
|
|
|
await write_image(image_name, image_path, response.content.iter_any(), images_repo, allow_raw_image=True)
|
2021-10-10 07:05:11 +00:00
|
|
|
except (OSError, InvalidImageError) as e:
|
|
|
|
raise ControllerError(f"Could not save {image_type} image '{image_path}': {e}")
|
|
|
|
except ClientError as e:
|
|
|
|
raise ControllerError(f"Could not connect to download '{image_name}': {e}")
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
raise ControllerError(f"Timeout while downloading '{image_name}' from '{image_url}'")
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
async def _find_appliance_version_images(
|
|
|
|
self,
|
|
|
|
appliance: Appliance,
|
|
|
|
version: dict,
|
|
|
|
images_repo: ImagesRepository,
|
|
|
|
image_dir: str
|
|
|
|
) -> None:
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
|
|
|
Find all the images belonging to a specific appliance version.
|
|
|
|
"""
|
|
|
|
|
|
|
|
version_images = version.get("images")
|
|
|
|
if version_images:
|
|
|
|
for appliance_key, appliance_file in version_images.items():
|
|
|
|
for image in appliance.images:
|
|
|
|
if appliance_file == image.get("filename"):
|
|
|
|
image_checksum = image.get("md5sum")
|
|
|
|
image_in_db = await images_repo.get_image_by_checksum(image_checksum)
|
|
|
|
if image_in_db:
|
|
|
|
version_images[appliance_key] = image_in_db.filename
|
|
|
|
else:
|
|
|
|
# check if the image is on disk
|
2022-04-18 10:13:52 +00:00
|
|
|
# FIXME: still necessary? the image should have been discovered and saved in the db already
|
2021-10-10 07:05:11 +00:00
|
|
|
image_path = os.path.join(image_dir, appliance_file)
|
2022-04-18 10:13:52 +00:00
|
|
|
if os.path.exists(image_path) and \
|
|
|
|
await wait_run_in_executor(
|
|
|
|
md5sum,
|
|
|
|
image_path,
|
|
|
|
cache_to_md5file=False
|
|
|
|
) == image_checksum:
|
2021-10-10 07:05:11 +00:00
|
|
|
async with aiofiles.open(image_path, "rb") as f:
|
2022-07-22 10:39:52 +00:00
|
|
|
await write_image(appliance_file, image_path, f, images_repo, allow_raw_image=True)
|
2021-10-10 07:05:11 +00:00
|
|
|
else:
|
|
|
|
# download the image if there is a direct download URL
|
|
|
|
direct_download_url = image.get("direct_download_url")
|
|
|
|
if direct_download_url:
|
|
|
|
await self._download_image(
|
|
|
|
image_dir,
|
|
|
|
appliance_file,
|
|
|
|
appliance.type,
|
|
|
|
direct_download_url,
|
|
|
|
images_repo)
|
|
|
|
else:
|
|
|
|
raise ControllerError(f"Could not find '{appliance_file}'")
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
async def _create_template(self, template_data, templates_repo, rbac_repo, current_user):
|
|
|
|
"""
|
|
|
|
Create a new template
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
template_create = schemas.TemplateCreate(**template_data)
|
|
|
|
except ValidationError as e:
|
|
|
|
raise ControllerError(message=f"Could not validate template data: {e}")
|
|
|
|
template = await TemplatesService(templates_repo).create_template(template_create)
|
2023-08-27 08:20:42 +00:00
|
|
|
#template_id = template.get("template_id")
|
|
|
|
#await rbac_repo.add_permission_to_user_with_path(current_user.user_id, f"/templates/{template_id}/*")
|
2021-10-18 07:34:30 +00:00
|
|
|
log.info(f"Template '{template.get('name')}' has been created")
|
|
|
|
|
|
|
|
async def _appliance_to_template(self, appliance: Appliance, version: str = None) -> dict:
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
2021-10-18 07:34:30 +00:00
|
|
|
Get template data from appliance
|
2021-10-10 07:05:11 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
from . import Controller
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
# downloading missing custom symbol for this appliance
|
|
|
|
if appliance.symbol and not appliance.symbol.startswith(":/symbols/"):
|
|
|
|
destination_path = os.path.join(Controller.instance().symbols.symbols_path(), appliance.symbol)
|
|
|
|
if not os.path.exists(destination_path):
|
|
|
|
await self._download_symbol(appliance.symbol, destination_path)
|
|
|
|
return ApplianceToTemplate().new_template(appliance.asdict(), version, "local") # FIXME: "local"
|
|
|
|
|
|
|
|
async def install_appliances_from_image(
|
|
|
|
self,
|
|
|
|
image_path: str,
|
|
|
|
image_checksum: str,
|
|
|
|
images_repo: ImagesRepository,
|
|
|
|
templates_repo: TemplatesRepository,
|
|
|
|
rbac_repo: RbacRepository,
|
|
|
|
current_user: schemas.User,
|
|
|
|
image_dir: str
|
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Install appliances using an image checksum
|
|
|
|
"""
|
|
|
|
|
|
|
|
appliances_info = self._find_appliances_from_image_checksum(image_checksum)
|
|
|
|
for appliance, image_version in appliances_info:
|
2021-10-18 11:16:50 +00:00
|
|
|
try:
|
2023-08-04 08:20:06 +00:00
|
|
|
schemas.Appliance.model_validate(appliance.asdict())
|
2021-10-18 11:16:50 +00:00
|
|
|
except ValidationError as e:
|
2022-03-20 06:20:17 +00:00
|
|
|
log.warning(f"Could not validate appliance '{appliance.id}': {e}")
|
2021-10-10 07:05:11 +00:00
|
|
|
if appliance.versions:
|
|
|
|
for version in appliance.versions:
|
|
|
|
if version.get("name") == image_version:
|
2021-10-18 07:34:30 +00:00
|
|
|
try:
|
|
|
|
await self._find_appliance_version_images(appliance, version, images_repo, image_dir)
|
|
|
|
template_data = await self._appliance_to_template(appliance, version)
|
|
|
|
await self._create_template(template_data, templates_repo, rbac_repo, current_user)
|
|
|
|
except (ControllerError, InvalidImageError) as e:
|
|
|
|
log.warning(f"Could not automatically create template using image '{image_path}': {e}")
|
|
|
|
|
|
|
|
async def install_appliance(
|
|
|
|
self,
|
|
|
|
appliance_id: UUID,
|
|
|
|
version: str,
|
|
|
|
images_repo: ImagesRepository,
|
|
|
|
templates_repo: TemplatesRepository,
|
|
|
|
rbac_repo: RbacRepository,
|
|
|
|
current_user: schemas.User
|
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
Install a new appliance
|
|
|
|
"""
|
|
|
|
|
|
|
|
appliance = self._appliances.get(str(appliance_id))
|
|
|
|
if not appliance:
|
|
|
|
raise ControllerNotFoundError(message=f"Could not find appliance '{appliance_id}'")
|
|
|
|
|
2021-10-18 11:16:50 +00:00
|
|
|
try:
|
2023-08-04 08:20:06 +00:00
|
|
|
schemas.Appliance.model_validate(appliance.asdict())
|
2021-10-18 11:16:50 +00:00
|
|
|
except ValidationError as e:
|
|
|
|
raise ControllerError(message=f"Could not validate appliance '{appliance_id}': {e}")
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
if version:
|
|
|
|
if not appliance.versions:
|
|
|
|
raise ControllerBadRequestError(message=f"Appliance '{appliance_id}' do not have versions")
|
|
|
|
|
|
|
|
image_dir = default_images_directory(appliance.type)
|
|
|
|
for appliance_version_info in appliance.versions:
|
|
|
|
if appliance_version_info.get("name") == version:
|
|
|
|
try:
|
|
|
|
await self._find_appliance_version_images(appliance, appliance_version_info, images_repo, image_dir)
|
|
|
|
except InvalidImageError as e:
|
|
|
|
raise ControllerError(message=f"Image error: {e}")
|
|
|
|
template_data = await self._appliance_to_template(appliance, appliance_version_info)
|
|
|
|
return await self._create_template(template_data, templates_repo, rbac_repo, current_user)
|
|
|
|
|
|
|
|
raise ControllerNotFoundError(message=f"Could not find version '{version}' in appliance '{appliance_id}'")
|
|
|
|
|
|
|
|
else:
|
|
|
|
if appliance.versions:
|
|
|
|
# TODO: install appliance versions based on available images
|
|
|
|
raise ControllerBadRequestError(message=f"Selecting a version is required to install "
|
|
|
|
f"appliance '{appliance_id}'")
|
|
|
|
|
|
|
|
template_data = await self._appliance_to_template(appliance)
|
|
|
|
await self._create_template(template_data, templates_repo, rbac_repo, current_user)
|
2021-08-11 07:28:23 +00:00
|
|
|
|
2022-07-25 18:39:03 +00:00
|
|
|
def load_appliances(self, symbol_theme: str = None) -> None:
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
|
|
|
Loads appliance files from disk.
|
|
|
|
"""
|
|
|
|
|
|
|
|
self._appliances = {}
|
2021-04-13 09:16:50 +00:00
|
|
|
for directory, builtin in (
|
|
|
|
(
|
2022-11-09 12:30:28 +00:00
|
|
|
self._builtin_appliances_path(),
|
2021-04-13 09:16:50 +00:00
|
|
|
True,
|
|
|
|
),
|
|
|
|
(
|
2022-11-09 12:30:28 +00:00
|
|
|
self._custom_appliances_path(),
|
2021-04-13 09:16:50 +00:00
|
|
|
False,
|
|
|
|
),
|
|
|
|
):
|
2019-01-14 09:09:06 +00:00
|
|
|
if directory and os.path.isdir(directory):
|
|
|
|
for file in os.listdir(directory):
|
2021-04-13 09:16:50 +00:00
|
|
|
if not file.endswith(".gns3a") and not file.endswith(".gns3appliance"):
|
2019-01-14 09:09:06 +00:00
|
|
|
continue
|
|
|
|
path = os.path.join(directory, file)
|
|
|
|
try:
|
2021-04-13 09:16:50 +00:00
|
|
|
with open(path, encoding="utf-8") as f:
|
2021-10-18 11:42:10 +00:00
|
|
|
appliance = Appliance(path, json.load(f), builtin=builtin)
|
|
|
|
json_data = appliance.asdict() # Check if loaded without error
|
2021-04-13 09:16:50 +00:00
|
|
|
if appliance.status != "broken":
|
2023-08-04 08:20:06 +00:00
|
|
|
schemas.Appliance.model_validate(json_data)
|
2021-10-18 07:34:30 +00:00
|
|
|
self._appliances[appliance.id] = appliance
|
2019-03-12 11:13:33 +00:00
|
|
|
if not appliance.symbol or appliance.symbol.startswith(":/symbols/"):
|
|
|
|
# apply a default symbol if the appliance has none or a default symbol
|
2021-10-18 11:42:10 +00:00
|
|
|
default_symbol = self._get_default_symbol(json_data, symbol_theme)
|
2019-03-12 11:13:33 +00:00
|
|
|
if default_symbol:
|
|
|
|
appliance.symbol = default_symbol
|
2021-10-18 11:16:50 +00:00
|
|
|
except (ValueError, OSError, KeyError, ValidationError) as e:
|
2021-10-18 11:42:10 +00:00
|
|
|
print(f"Cannot load appliance file '{path}': {e}")
|
2019-01-14 09:09:06 +00:00
|
|
|
continue
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
def _get_default_symbol(self, appliance: dict, symbol_theme: str) -> str:
|
2019-03-12 11:13:33 +00:00
|
|
|
"""
|
|
|
|
Returns the default symbol for a given appliance.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from . import Controller
|
2021-04-13 09:16:50 +00:00
|
|
|
|
2019-03-12 11:13:33 +00:00
|
|
|
controller = Controller.instance()
|
2022-07-25 18:39:03 +00:00
|
|
|
if not symbol_theme:
|
|
|
|
symbol_theme = controller.symbols.theme
|
2019-03-12 11:13:33 +00:00
|
|
|
category = appliance["category"]
|
|
|
|
if category == "guest":
|
|
|
|
if "docker" in appliance:
|
|
|
|
return controller.symbols.get_default_symbol("docker_guest", symbol_theme)
|
|
|
|
elif "qemu" in appliance:
|
|
|
|
return controller.symbols.get_default_symbol("qemu_guest", symbol_theme)
|
|
|
|
return controller.symbols.get_default_symbol(category, symbol_theme)
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
async def download_custom_symbols(self) -> None:
|
2019-03-11 09:55:16 +00:00
|
|
|
"""
|
|
|
|
Download custom appliance symbols from our GitHub registry repository.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from . import Controller
|
2021-04-13 09:16:50 +00:00
|
|
|
|
2019-03-11 09:55:16 +00:00
|
|
|
symbol_dir = Controller.instance().symbols.symbols_path()
|
|
|
|
self.load_appliances()
|
|
|
|
for appliance in self._appliances.values():
|
|
|
|
symbol = appliance.symbol
|
|
|
|
if symbol and not symbol.startswith(":/symbols/"):
|
|
|
|
destination_path = os.path.join(symbol_dir, symbol)
|
|
|
|
if not os.path.exists(destination_path):
|
|
|
|
await self._download_symbol(symbol, destination_path)
|
|
|
|
|
|
|
|
# refresh the symbol cache
|
|
|
|
Controller.instance().symbols.list()
|
|
|
|
|
2021-10-18 07:34:30 +00:00
|
|
|
async def _download_symbol(self, symbol: str, destination_path: str) -> None:
|
2019-03-11 09:55:16 +00:00
|
|
|
"""
|
|
|
|
Download a custom appliance symbol from our GitHub registry repository.
|
|
|
|
"""
|
|
|
|
|
2021-04-13 09:07:58 +00:00
|
|
|
symbol_url = f"https://raw.githubusercontent.com/GNS3/gns3-registry/master/symbols/{symbol}"
|
2021-10-10 07:05:11 +00:00
|
|
|
log.info(f"Downloading symbol '{symbol}'")
|
2020-10-22 05:49:44 +00:00
|
|
|
async with HTTPClient.get(symbol_url) as response:
|
|
|
|
if response.status != 200:
|
2021-04-13 09:16:50 +00:00
|
|
|
log.warning(
|
|
|
|
f"Could not retrieve appliance symbol {symbol} from GitHub due to HTTP error code {response.status}"
|
|
|
|
)
|
2020-10-22 05:49:44 +00:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
symbol_data = await response.read()
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Saving {symbol} symbol to {destination_path}")
|
2021-04-13 09:16:50 +00:00
|
|
|
with open(destination_path, "wb") as f:
|
2020-10-22 05:49:44 +00:00
|
|
|
f.write(symbol_data)
|
|
|
|
except asyncio.TimeoutError:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.warning(f"Timeout while downloading '{symbol_url}'")
|
2020-10-22 05:49:44 +00:00
|
|
|
except OSError as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.warning(f"Could not write appliance symbol '{destination_path}': {e}")
|
2019-03-11 09:55:16 +00:00
|
|
|
|
2019-01-14 09:09:06 +00:00
|
|
|
@locking
|
2021-10-18 07:34:30 +00:00
|
|
|
async def download_appliances(self) -> None:
|
2019-01-14 09:09:06 +00:00
|
|
|
"""
|
|
|
|
Downloads appliance files from GitHub registry repository.
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
headers = {}
|
|
|
|
if self._appliances_etag:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Checking if appliances are up-to-date (ETag {self._appliances_etag})")
|
2019-01-14 09:09:06 +00:00
|
|
|
headers["If-None-Match"] = self._appliances_etag
|
2020-10-22 05:49:44 +00:00
|
|
|
|
2021-04-13 09:16:50 +00:00
|
|
|
async with HTTPClient.get(
|
|
|
|
"https://api.github.com/repos/GNS3/gns3-registry/contents/appliances", headers=headers
|
|
|
|
) as response:
|
2020-10-22 05:49:44 +00:00
|
|
|
if response.status == 304:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Appliances are already up-to-date (ETag {self._appliances_etag})")
|
2020-10-22 05:49:44 +00:00
|
|
|
return
|
|
|
|
elif response.status != 200:
|
2021-04-13 09:16:50 +00:00
|
|
|
raise ControllerError(
|
|
|
|
f"Could not retrieve appliances from GitHub due to HTTP error code {response.status}"
|
|
|
|
)
|
2020-10-22 05:49:44 +00:00
|
|
|
etag = response.headers.get("ETag")
|
|
|
|
if etag:
|
|
|
|
self._appliances_etag = etag
|
|
|
|
from . import Controller
|
2021-04-13 09:16:50 +00:00
|
|
|
|
2020-10-22 05:49:44 +00:00
|
|
|
Controller.instance().save()
|
|
|
|
json_data = await response.json()
|
2022-11-09 12:30:28 +00:00
|
|
|
appliances_dir = self._builtin_appliances_path()
|
2021-04-10 03:16:40 +00:00
|
|
|
downloaded_appliance_files = []
|
2020-10-22 05:49:44 +00:00
|
|
|
for appliance in json_data:
|
|
|
|
if appliance["type"] == "file":
|
|
|
|
appliance_name = appliance["name"]
|
|
|
|
log.info("Download appliance file from '{}'".format(appliance["download_url"]))
|
|
|
|
async with HTTPClient.get(appliance["download_url"]) as response:
|
|
|
|
if response.status != 200:
|
2021-04-13 09:16:50 +00:00
|
|
|
log.warning(
|
|
|
|
"Could not download '{}' due to HTTP error code {}".format(
|
|
|
|
appliance["download_url"], response.status
|
|
|
|
)
|
|
|
|
)
|
2020-10-22 05:49:44 +00:00
|
|
|
continue
|
|
|
|
try:
|
|
|
|
appliance_data = await response.read()
|
|
|
|
except asyncio.TimeoutError:
|
|
|
|
log.warning("Timeout while downloading '{}'".format(appliance["download_url"]))
|
|
|
|
continue
|
|
|
|
path = os.path.join(appliances_dir, appliance_name)
|
|
|
|
try:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Saving {appliance_name} file to {path}")
|
2021-04-13 09:16:50 +00:00
|
|
|
with open(path, "wb") as f:
|
2020-10-22 05:49:44 +00:00
|
|
|
f.write(appliance_data)
|
|
|
|
except OSError as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
raise ControllerError(f"Could not write appliance file '{path}': {e}")
|
2021-04-06 08:08:11 +00:00
|
|
|
downloaded_appliance_files.append(appliance_name)
|
|
|
|
|
2021-04-10 03:16:40 +00:00
|
|
|
# delete old appliance files
|
|
|
|
for filename in os.listdir(appliances_dir):
|
|
|
|
file_path = os.path.join(appliances_dir, filename)
|
|
|
|
if filename in downloaded_appliance_files:
|
|
|
|
continue
|
|
|
|
try:
|
|
|
|
if os.path.isfile(file_path) or os.path.islink(file_path):
|
2021-04-13 09:07:58 +00:00
|
|
|
log.info(f"Deleting old appliance file {file_path}")
|
2021-04-10 03:16:40 +00:00
|
|
|
os.unlink(file_path)
|
|
|
|
except OSError as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
log.warning(f"Could not delete old appliance file '{file_path}': {e}")
|
2021-04-10 03:16:40 +00:00
|
|
|
continue
|
2021-04-06 08:08:11 +00:00
|
|
|
|
2019-01-14 09:09:06 +00:00
|
|
|
except ValueError as e:
|
2021-04-13 09:07:58 +00:00
|
|
|
raise ControllerError(f"Could not read appliances information from GitHub: {e}")
|
2019-03-11 09:55:16 +00:00
|
|
|
|
|
|
|
# download the custom symbols
|
|
|
|
await self.download_custom_symbols()
|