mirror of
https://github.com/GNS3/gns3-server.git
synced 2025-06-22 08:50:09 +00:00
Use pyupgrade with --py36-plus param.
This commit is contained in:
@ -190,9 +190,9 @@ class Compute:
|
||||
# Due to random user generated by 1.4 it's common to have a very long user
|
||||
if len(user) > 14:
|
||||
user = user[:11] + "..."
|
||||
self._name = "{}://{}@{}:{}".format(self._protocol, user, self._host, self._port)
|
||||
self._name = f"{self._protocol}://{user}@{self._host}:{self._port}"
|
||||
else:
|
||||
self._name = "{}://{}:{}".format(self._protocol, self._host, self._port)
|
||||
self._name = f"{self._protocol}://{self._host}:{self._port}"
|
||||
|
||||
@property
|
||||
def connected(self):
|
||||
@ -321,10 +321,10 @@ class Compute:
|
||||
:returns: A file stream
|
||||
"""
|
||||
|
||||
url = self._getUrl("/projects/{}/files/{}".format(project.id, path))
|
||||
url = self._getUrl(f"/projects/{project.id}/files/{path}")
|
||||
response = await self._session().request("GET", url, auth=self._auth)
|
||||
if response.status == 404:
|
||||
raise ControllerNotFoundError("{} not found on compute".format(path))
|
||||
raise ControllerNotFoundError(f"{path} not found on compute")
|
||||
return response
|
||||
|
||||
async def download_image(self, image_type, image):
|
||||
@ -336,10 +336,10 @@ class Compute:
|
||||
:returns: A file stream
|
||||
"""
|
||||
|
||||
url = self._getUrl("/{}/images/{}".format(image_type, image))
|
||||
url = self._getUrl(f"/{image_type}/images/{image}")
|
||||
response = await self._session().request("GET", url, auth=self._auth)
|
||||
if response.status == 404:
|
||||
raise ControllerNotFoundError("{} not found on compute".format(image))
|
||||
raise ControllerNotFoundError(f"{image} not found on compute")
|
||||
return response
|
||||
|
||||
async def http_query(self, method, path, data=None, dont_connect=False, **kwargs):
|
||||
@ -352,7 +352,7 @@ class Compute:
|
||||
await self._controller.gns3vm.start()
|
||||
await self.connect()
|
||||
if not self._connected and not dont_connect:
|
||||
raise ComputeError("Cannot connect to compute '{}' with request {} {}".format(self._name, method, path))
|
||||
raise ComputeError(f"Cannot connect to compute '{self._name}' with request {method} {path}")
|
||||
response = await self._run_http_query(method, path, data=data, **kwargs)
|
||||
return response
|
||||
|
||||
@ -373,33 +373,33 @@ class Compute:
|
||||
|
||||
if not self._connected and not self._closed and self.host:
|
||||
try:
|
||||
log.info("Connecting to compute '{}'".format(self._id))
|
||||
log.info(f"Connecting to compute '{self._id}'")
|
||||
response = await self._run_http_query("GET", "/capabilities")
|
||||
except ComputeError as e:
|
||||
log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
|
||||
log.warning(f"Cannot connect to compute '{self._id}': {e}")
|
||||
# Try to reconnect after 5 seconds if server unavailable only if not during tests (otherwise we create a ressource usage bomb)
|
||||
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
|
||||
if self.id != "local" and self.id != "vm" and not self._controller.compute_has_open_project(self):
|
||||
log.warning("Not reconnecting to compute '{}' because there is no project opened on it".format(self._id))
|
||||
log.warning(f"Not reconnecting to compute '{self._id}' because there is no project opened on it")
|
||||
return
|
||||
self._connection_failure += 1
|
||||
# After 5 failure we close the project using the compute to avoid sync issues
|
||||
if self._connection_failure == 10:
|
||||
log.error("Could not connect to compute '{}' after multiple attempts: {}".format(self._id, e))
|
||||
log.error(f"Could not connect to compute '{self._id}' after multiple attempts: {e}")
|
||||
await self._controller.close_compute_projects(self)
|
||||
asyncio.get_event_loop().call_later(5, lambda: asyncio.ensure_future(self._try_reconnect()))
|
||||
return
|
||||
except web.HTTPNotFound:
|
||||
raise ControllerNotFoundError("The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
|
||||
raise ControllerNotFoundError(f"The server {self._id} is not a GNS3 server or it's a 1.X server")
|
||||
except web.HTTPUnauthorized:
|
||||
raise ControllerUnauthorizedError("Invalid auth for server {}".format(self._id))
|
||||
raise ControllerUnauthorizedError(f"Invalid auth for server {self._id}")
|
||||
except web.HTTPServiceUnavailable:
|
||||
raise ControllerNotFoundError("The server {} is unavailable".format(self._id))
|
||||
raise ControllerNotFoundError(f"The server {self._id} is unavailable")
|
||||
except ValueError:
|
||||
raise ComputeError("Invalid server url for server {}".format(self._id))
|
||||
raise ComputeError(f"Invalid server url for server {self._id}")
|
||||
|
||||
if "version" not in response.json:
|
||||
msg = "The server {} is not a GNS3 server".format(self._id)
|
||||
msg = f"The server {self._id} is not a GNS3 server"
|
||||
log.error(msg)
|
||||
await self._http_session.close()
|
||||
raise ControllerNotFoundError(msg)
|
||||
@ -426,7 +426,7 @@ class Compute:
|
||||
self._last_error = msg
|
||||
raise ControllerError(msg)
|
||||
else:
|
||||
msg = "{}\nUsing different versions may result in unexpected problems. Please use at your own risk.".format(msg)
|
||||
msg = f"{msg}\nUsing different versions may result in unexpected problems. Please use at your own risk."
|
||||
self._controller.notification.controller_emit("log.warning", {"message": msg})
|
||||
|
||||
self._notifications = asyncio.gather(self._connect_notification())
|
||||
@ -443,7 +443,7 @@ class Compute:
|
||||
ws_url = self._getUrl("/notifications/ws")
|
||||
try:
|
||||
async with self._session().ws_connect(ws_url, auth=self._auth, heartbeat=10) as ws:
|
||||
log.info("Connected to compute '{}' WebSocket '{}'".format(self._id, ws_url))
|
||||
log.info(f"Connected to compute '{self._id}' WebSocket '{ws_url}'")
|
||||
async for response in ws:
|
||||
if response.type == aiohttp.WSMsgType.TEXT:
|
||||
msg = json.loads(response.data)
|
||||
@ -462,19 +462,19 @@ class Compute:
|
||||
if response.type == aiohttp.WSMsgType.CLOSE:
|
||||
await ws.close()
|
||||
elif response.type == aiohttp.WSMsgType.ERROR:
|
||||
log.error("Error received on compute '{}' WebSocket '{}': {}".format(self._id, ws_url, ws.exception()))
|
||||
log.error(f"Error received on compute '{self._id}' WebSocket '{ws_url}': {ws.exception()}")
|
||||
elif response.type == aiohttp.WSMsgType.CLOSED:
|
||||
pass
|
||||
break
|
||||
except aiohttp.ClientError as e:
|
||||
log.error("Client response error received on compute '{}' WebSocket '{}': {}".format(self._id, ws_url,e))
|
||||
log.error(f"Client response error received on compute '{self._id}' WebSocket '{ws_url}': {e}")
|
||||
finally:
|
||||
self._connected = False
|
||||
log.info("Connection closed to compute '{}' WebSocket '{}'".format(self._id, ws_url))
|
||||
log.info(f"Connection closed to compute '{self._id}' WebSocket '{ws_url}'")
|
||||
|
||||
# Try to reconnect after 1 second if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
|
||||
if self.id != "local" and not hasattr(sys, "_called_from_test") or not sys._called_from_test:
|
||||
log.info("Reconnecting to to compute '{}' WebSocket '{}'".format(self._id, ws_url))
|
||||
log.info(f"Reconnecting to to compute '{self._id}' WebSocket '{ws_url}'")
|
||||
asyncio.get_event_loop().call_later(1, lambda: asyncio.ensure_future(self.connect()))
|
||||
|
||||
self._cpu_usage_percent = None
|
||||
@ -492,10 +492,10 @@ class Compute:
|
||||
host = str(ipaddress.IPv6Address(host))
|
||||
if host == "::":
|
||||
host = "::1"
|
||||
host = "[{}]".format(host)
|
||||
host = f"[{host}]"
|
||||
elif host == "0.0.0.0":
|
||||
host = "127.0.0.1"
|
||||
return "{}://{}:{}/v3/compute{}".format(self._protocol, host, self._port, path)
|
||||
return f"{self._protocol}://{host}:{self._port}/v3/compute{path}"
|
||||
|
||||
def get_url(self, path):
|
||||
""" Returns URL for specific path at Compute"""
|
||||
@ -524,10 +524,10 @@ class Compute:
|
||||
else:
|
||||
data = json.dumps(data).encode("utf-8")
|
||||
try:
|
||||
log.debug("Attempting request to compute: {method} {url} {headers}".format(method=method, url=url, headers=headers))
|
||||
log.debug(f"Attempting request to compute: {method} {url} {headers}")
|
||||
response = await self._session().request(method, url, headers=headers, data=data, auth=self._auth, chunked=chunked, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
raise ComputeError("Timeout error for {} call to {} after {}s".format(method, url, timeout))
|
||||
raise ComputeError(f"Timeout error for {method} call to {url} after {timeout}s")
|
||||
except (aiohttp.ClientError, aiohttp.ServerDisconnectedError, aiohttp.ClientResponseError, ValueError, KeyError, socket.gaierror) as e:
|
||||
# aiohttp 2.3.1 raises socket.gaierror when cannot find host
|
||||
raise ComputeError(str(e))
|
||||
@ -546,13 +546,13 @@ class Compute:
|
||||
msg = ""
|
||||
|
||||
if response.status == 401:
|
||||
raise ControllerUnauthorizedError("Invalid authentication for compute {}".format(self.id))
|
||||
raise ControllerUnauthorizedError(f"Invalid authentication for compute {self.id}")
|
||||
elif response.status == 403:
|
||||
raise ControllerForbiddenError(msg)
|
||||
elif response.status == 404:
|
||||
raise ControllerNotFoundError("{} {} not found".format(method, path))
|
||||
raise ControllerNotFoundError(f"{method} {path} not found")
|
||||
elif response.status == 408 or response.status == 504:
|
||||
raise ControllerTimeoutError("{} {} request timeout".format(method, path))
|
||||
raise ControllerTimeoutError(f"{method} {path} request timeout")
|
||||
elif response.status == 409:
|
||||
try:
|
||||
raise ComputeConflict(json.loads(body))
|
||||
@ -560,11 +560,11 @@ class Compute:
|
||||
except ValueError:
|
||||
raise ControllerError(msg)
|
||||
elif response.status == 500:
|
||||
raise aiohttp.web.HTTPInternalServerError(text="Internal server error {}".format(url))
|
||||
raise aiohttp.web.HTTPInternalServerError(text=f"Internal server error {url}")
|
||||
elif response.status == 503:
|
||||
raise aiohttp.web.HTTPServiceUnavailable(text="Service unavailable {} {}".format(url, body))
|
||||
raise aiohttp.web.HTTPServiceUnavailable(text=f"Service unavailable {url} {body}")
|
||||
else:
|
||||
raise NotImplementedError("{} status code is not supported for {} '{}'".format(response.status, method, url))
|
||||
raise NotImplementedError(f"{response.status} status code is not supported for {method} '{url}'")
|
||||
if body and len(body):
|
||||
if raw:
|
||||
response.body = body
|
||||
@ -572,7 +572,7 @@ class Compute:
|
||||
try:
|
||||
response.json = json.loads(body)
|
||||
except ValueError:
|
||||
raise ControllerError("The server {} is not a GNS3 server".format(self._id))
|
||||
raise ControllerError(f"The server {self._id} is not a GNS3 server")
|
||||
else:
|
||||
response.json = {}
|
||||
response.body = b""
|
||||
@ -597,7 +597,7 @@ class Compute:
|
||||
Forward a call to the emulator on compute
|
||||
"""
|
||||
try:
|
||||
action = "/{}/{}".format(type, path)
|
||||
action = f"/{type}/{path}"
|
||||
res = await self.http_query(method, action, data=data, timeout=None)
|
||||
except aiohttp.ServerDisconnectedError:
|
||||
raise ControllerError(f"Connection lost to {self._id} during {method} {action}")
|
||||
@ -609,7 +609,7 @@ class Compute:
|
||||
"""
|
||||
images = []
|
||||
|
||||
res = await self.http_query("GET", "/{}/images".format(type), timeout=None)
|
||||
res = await self.http_query("GET", f"/{type}/images", timeout=None)
|
||||
images = res.json
|
||||
|
||||
try:
|
||||
@ -621,14 +621,14 @@ class Compute:
|
||||
else:
|
||||
images = sorted(images, key=itemgetter('image'))
|
||||
except OSError as e:
|
||||
raise ComputeError("Cannot list images: {}".format(str(e)))
|
||||
raise ComputeError(f"Cannot list images: {str(e)}")
|
||||
return images
|
||||
|
||||
async def list_files(self, project):
|
||||
"""
|
||||
List files in the project on computes
|
||||
"""
|
||||
path = "/projects/{}/files".format(project.id)
|
||||
path = f"/projects/{project.id}/files"
|
||||
res = await self.http_query("GET", path, timeout=None)
|
||||
return res.json
|
||||
|
||||
@ -676,4 +676,4 @@ class Compute:
|
||||
if this_network.overlaps(other_network):
|
||||
return this_interface["ip_address"], other_interface["ip_address"]
|
||||
|
||||
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
|
||||
raise ValueError(f"No common subnet for compute {self.name} and {other_compute.name}")
|
||||
|
Reference in New Issue
Block a user