2016-03-03 15:02:27 +00:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Copyright (C) 2016 GNS3 Technologies Inc.
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2016-03-10 09:32:07 +00:00
|
|
|
import aiohttp
|
|
|
|
import asyncio
|
|
|
|
import json
|
2016-05-25 12:10:03 +00:00
|
|
|
import uuid
|
2016-06-08 12:14:03 +00:00
|
|
|
import os
|
2016-06-07 17:38:01 +00:00
|
|
|
import io
|
2016-03-03 15:02:27 +00:00
|
|
|
|
2016-05-14 00:48:10 +00:00
|
|
|
from ..utils import parse_version
|
2016-06-08 12:14:03 +00:00
|
|
|
from ..utils.images import scan_for_images
|
2016-03-04 15:11:31 +00:00
|
|
|
from ..controller.controller_error import ControllerError
|
|
|
|
from ..config import Config
|
2016-03-04 15:58:53 +00:00
|
|
|
from ..version import __version__
|
|
|
|
|
2016-03-04 15:11:31 +00:00
|
|
|
|
2016-03-04 15:55:59 +00:00
|
|
|
import logging
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2016-03-04 15:11:31 +00:00
|
|
|
|
2016-04-15 15:57:06 +00:00
|
|
|
class ComputeError(ControllerError):
|
2016-03-04 15:11:31 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
2016-06-07 17:38:01 +00:00
|
|
|
class ComputeConflict(aiohttp.web.HTTPConflict):
|
|
|
|
"""
|
|
|
|
Raise when the compute send a 409 that we can handle
|
|
|
|
|
|
|
|
:param response: The response of the compute
|
|
|
|
"""
|
2016-06-08 12:14:03 +00:00
|
|
|
|
2016-06-07 17:38:01 +00:00
|
|
|
def __init__(self, response):
|
|
|
|
super().__init__(text=response["message"])
|
|
|
|
self.response = response
|
|
|
|
|
|
|
|
|
2016-06-07 09:21:19 +00:00
|
|
|
class Timeout(aiohttp.Timeout):
|
|
|
|
"""
|
|
|
|
Could be removed with aiohttp 0.22 that support None timeout
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
if self._timeout:
|
|
|
|
return super().__enter__()
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
if self._timeout:
|
|
|
|
return super().__exit__(exc_type, exc_val, exc_tb)
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
2016-04-15 15:57:06 +00:00
|
|
|
class Compute:
|
2016-03-03 15:02:27 +00:00
|
|
|
"""
|
2016-04-15 15:57:06 +00:00
|
|
|
A GNS3 compute.
|
2016-03-03 15:02:27 +00:00
|
|
|
"""
|
|
|
|
|
2016-05-25 12:10:03 +00:00
|
|
|
def __init__(self, compute_id, controller=None, protocol="http", host="localhost", port=3080, user=None, password=None, name=None):
|
2016-03-18 15:55:54 +00:00
|
|
|
assert controller is not None
|
2016-04-15 15:57:06 +00:00
|
|
|
log.info("Create compute %s", compute_id)
|
2016-05-25 12:10:03 +00:00
|
|
|
|
|
|
|
if compute_id is None:
|
|
|
|
self._id = str(uuid.uuid4())
|
|
|
|
else:
|
|
|
|
self._id = compute_id
|
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
self.protocol = protocol
|
|
|
|
self.host = host
|
|
|
|
self.port = port
|
2016-03-16 14:55:07 +00:00
|
|
|
self._user = None
|
|
|
|
self._password = None
|
2016-03-03 15:02:27 +00:00
|
|
|
self._connected = False
|
2016-03-18 15:55:54 +00:00
|
|
|
self._controller = controller
|
2016-05-11 21:19:00 +00:00
|
|
|
self._set_auth(user, password)
|
2016-04-15 15:57:06 +00:00
|
|
|
self._session = aiohttp.ClientSession()
|
2016-05-11 14:31:16 +00:00
|
|
|
self._version = None
|
2016-05-23 09:20:52 +00:00
|
|
|
self.name = name
|
2016-03-03 15:02:27 +00:00
|
|
|
|
2016-06-01 23:50:31 +00:00
|
|
|
# It's a configuration issue if the compute is not configured to be local but the compute id is local
|
2016-04-15 15:57:06 +00:00
|
|
|
if compute_id == "local" and Config.instance().get_section_config("Server")["local"] is False:
|
|
|
|
raise ComputeError("The local compute is started without --local")
|
2016-03-04 15:11:31 +00:00
|
|
|
|
2016-03-18 15:55:54 +00:00
|
|
|
def __del__(self):
|
|
|
|
self._session.close()
|
|
|
|
|
2016-05-11 21:19:00 +00:00
|
|
|
def _set_auth(self, user, password):
|
2016-03-16 14:55:07 +00:00
|
|
|
"""
|
|
|
|
Set authentication parameters
|
|
|
|
"""
|
2016-05-26 08:11:11 +00:00
|
|
|
if user is None or len(user.strip()) == 0:
|
|
|
|
self._user = None
|
|
|
|
self._password = None
|
2016-03-16 14:55:07 +00:00
|
|
|
self._auth = None
|
2016-05-26 08:11:11 +00:00
|
|
|
else:
|
|
|
|
self._user = user.strip()
|
2016-05-26 11:32:52 +00:00
|
|
|
if password:
|
|
|
|
self._password = password.strip()
|
|
|
|
self._auth = aiohttp.BasicAuth(self._user, self._password)
|
|
|
|
else:
|
|
|
|
self._password = None
|
|
|
|
self._auth = aiohttp.BasicAuth(self._user, "")
|
2016-03-16 14:55:07 +00:00
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def update(self, **kwargs):
|
|
|
|
for kw in kwargs:
|
|
|
|
setattr(self, kw, kwargs[kw])
|
|
|
|
if self._session:
|
|
|
|
self._session.close()
|
|
|
|
self._connected = False
|
|
|
|
self._controller.notification.emit("compute.updated", self.__json__())
|
2016-06-08 12:25:11 +00:00
|
|
|
self._controller.save()
|
2016-05-25 09:27:41 +00:00
|
|
|
|
2016-06-02 11:44:12 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def close(self):
|
|
|
|
self._connected = False
|
|
|
|
self._session.close()
|
|
|
|
|
2016-05-11 14:31:16 +00:00
|
|
|
@property
|
|
|
|
def version(self):
|
|
|
|
"""
|
|
|
|
:returns: Version of compute node (string or None if not connected)
|
|
|
|
"""
|
|
|
|
return self._version
|
|
|
|
|
2016-05-23 09:20:52 +00:00
|
|
|
@property
|
|
|
|
def name(self):
|
|
|
|
"""
|
|
|
|
:returns: Compute name
|
|
|
|
"""
|
|
|
|
return self._name
|
|
|
|
|
|
|
|
@name.setter
|
|
|
|
def name(self, name):
|
|
|
|
if name is not None:
|
|
|
|
self._name = name
|
|
|
|
elif self._id == "local":
|
2016-05-23 16:44:20 +00:00
|
|
|
self._name = "Local"
|
2016-05-23 09:20:52 +00:00
|
|
|
else:
|
2016-05-25 11:58:29 +00:00
|
|
|
if self._user:
|
|
|
|
user = self._user
|
|
|
|
# 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)
|
|
|
|
else:
|
|
|
|
self._name = "{}://{}:{}".format(self._protocol, self._host, self._port)
|
2016-05-23 09:20:52 +00:00
|
|
|
|
2016-05-11 14:31:16 +00:00
|
|
|
@property
|
|
|
|
def connected(self):
|
|
|
|
"""
|
|
|
|
:returns: True if compute node is connected
|
|
|
|
"""
|
|
|
|
return self._connected
|
|
|
|
|
2016-03-03 15:02:27 +00:00
|
|
|
@property
|
|
|
|
def id(self):
|
|
|
|
"""
|
2016-04-15 15:57:06 +00:00
|
|
|
:returns: Compute identifier (string)
|
2016-03-03 15:02:27 +00:00
|
|
|
"""
|
|
|
|
return self._id
|
|
|
|
|
|
|
|
@property
|
|
|
|
def host(self):
|
|
|
|
"""
|
2016-04-15 15:57:06 +00:00
|
|
|
:returns: Compute host (string)
|
2016-03-03 15:02:27 +00:00
|
|
|
"""
|
|
|
|
return self._host
|
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@host.setter
|
|
|
|
def host(self, host):
|
|
|
|
self._host = host
|
|
|
|
|
2016-04-19 13:35:50 +00:00
|
|
|
@property
|
|
|
|
def port(self):
|
|
|
|
"""
|
|
|
|
:returns: Compute port (integer)
|
|
|
|
"""
|
|
|
|
return self._port
|
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@port.setter
|
|
|
|
def port(self, port):
|
|
|
|
self._port = port
|
|
|
|
|
2016-04-19 13:35:50 +00:00
|
|
|
@property
|
|
|
|
def protocol(self):
|
|
|
|
"""
|
|
|
|
:returns: Compute protocol (string)
|
|
|
|
"""
|
|
|
|
return self._protocol
|
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@protocol.setter
|
|
|
|
def protocol(self, protocol):
|
|
|
|
self._protocol = protocol
|
|
|
|
|
2016-03-16 14:55:07 +00:00
|
|
|
@property
|
|
|
|
def user(self):
|
|
|
|
return self._user
|
|
|
|
|
|
|
|
@user.setter
|
|
|
|
def user(self, value):
|
2016-05-11 21:19:00 +00:00
|
|
|
self._set_auth(value, self._password)
|
2016-03-16 14:55:07 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def password(self):
|
|
|
|
return self._password
|
|
|
|
|
2016-06-01 23:50:31 +00:00
|
|
|
@password.setter
|
2016-03-16 14:55:07 +00:00
|
|
|
def password(self, value):
|
2016-05-11 21:19:00 +00:00
|
|
|
self._set_auth(self._user, value)
|
2016-03-16 14:55:07 +00:00
|
|
|
|
2016-03-03 15:02:27 +00:00
|
|
|
def __json__(self):
|
|
|
|
return {
|
2016-04-15 15:57:06 +00:00
|
|
|
"compute_id": self._id,
|
2016-05-23 09:20:52 +00:00
|
|
|
"name": self._name,
|
2016-03-03 15:02:27 +00:00
|
|
|
"protocol": self._protocol,
|
|
|
|
"host": self._host,
|
|
|
|
"port": self._port,
|
|
|
|
"user": self._user,
|
2016-03-16 14:55:07 +00:00
|
|
|
"connected": self._connected
|
2016-03-03 15:02:27 +00:00
|
|
|
}
|
2016-03-10 09:32:07 +00:00
|
|
|
|
2016-04-22 14:22:03 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-11 21:19:00 +00:00
|
|
|
def steam_file(self, project, path):
|
2016-04-22 14:22:03 +00:00
|
|
|
"""
|
|
|
|
Read file of a project and stream it
|
|
|
|
|
|
|
|
:param project: A project object
|
|
|
|
:param path: The path of the file in the project
|
|
|
|
:returns: A file stream
|
|
|
|
"""
|
|
|
|
|
|
|
|
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
|
|
|
|
response = yield from self._session.request("GET", url, auth=self._auth)
|
|
|
|
if response.status == 404:
|
|
|
|
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
|
|
|
|
return response.content
|
|
|
|
|
2016-03-10 09:32:07 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def http_query(self, method, path, data=None, **kwargs):
|
2016-03-18 15:55:54 +00:00
|
|
|
if not self._connected:
|
|
|
|
yield from self._connect()
|
2016-04-20 14:24:30 +00:00
|
|
|
if not self._connected:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
|
2016-05-19 14:21:35 +00:00
|
|
|
response = yield from self._run_http_query(method, path, data=data, **kwargs)
|
2016-04-14 10:22:10 +00:00
|
|
|
return response
|
2016-03-18 15:55:54 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def _connect(self):
|
|
|
|
"""
|
|
|
|
Check if remote server is accessible
|
|
|
|
"""
|
2016-03-16 14:55:07 +00:00
|
|
|
if not self._connected:
|
2016-06-02 00:21:07 +00:00
|
|
|
response = yield from self._run_http_query("GET", "/version")
|
2016-04-20 14:24:30 +00:00
|
|
|
|
2016-03-16 14:55:07 +00:00
|
|
|
if "version" not in response.json:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
|
2016-05-11 14:31:16 +00:00
|
|
|
self._version = response.json["version"]
|
2016-03-16 14:55:07 +00:00
|
|
|
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
|
|
|
|
|
2016-05-11 21:19:00 +00:00
|
|
|
self._notifications = asyncio.async(self._connect_notification())
|
2016-03-18 15:55:54 +00:00
|
|
|
self._connected = True
|
2016-05-23 16:44:20 +00:00
|
|
|
self._controller.notification.emit("compute.updated", self.__json__())
|
2016-03-18 15:55:54 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
2016-05-11 21:19:00 +00:00
|
|
|
def _connect_notification(self):
|
2016-03-18 15:55:54 +00:00
|
|
|
"""
|
|
|
|
Connect to the notification stream
|
|
|
|
"""
|
2016-04-14 10:22:10 +00:00
|
|
|
ws = yield from self._session.ws_connect(self._getUrl("/notifications/ws"))
|
2016-03-18 15:55:54 +00:00
|
|
|
while True:
|
|
|
|
response = yield from ws.receive()
|
|
|
|
if response.tp == aiohttp.MsgType.closed or response.tp == aiohttp.MsgType.error:
|
|
|
|
self._connected = False
|
|
|
|
break
|
|
|
|
msg = json.loads(response.data)
|
|
|
|
action = msg.pop("action")
|
|
|
|
event = msg.pop("event")
|
2016-05-18 14:12:13 +00:00
|
|
|
self._controller.notification.dispatch(action, event, compute_id=self.id)
|
2016-03-18 15:55:54 +00:00
|
|
|
|
|
|
|
def _getUrl(self, path):
|
2016-04-15 15:57:06 +00:00
|
|
|
return "{}://{}:{}/v2/compute{}".format(self._protocol, self._host, self._port, path)
|
2016-03-16 14:55:07 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def _run_http_query(self, method, path, data=None, timeout=10):
|
2016-06-07 09:21:19 +00:00
|
|
|
with Timeout(timeout):
|
2016-03-18 15:55:54 +00:00
|
|
|
url = self._getUrl(path)
|
2016-06-06 17:51:35 +00:00
|
|
|
headers = {}
|
|
|
|
headers['content-type'] = 'application/json'
|
|
|
|
chunked = False
|
2016-04-14 10:22:10 +00:00
|
|
|
if data == {}:
|
|
|
|
data = None
|
|
|
|
elif data is not None:
|
2016-03-18 15:55:54 +00:00
|
|
|
if hasattr(data, '__json__'):
|
2016-06-06 17:51:35 +00:00
|
|
|
data = json.dumps(data.__json__())
|
|
|
|
# Stream the request
|
2016-06-07 17:38:01 +00:00
|
|
|
elif isinstance(data, aiohttp.streams.StreamReader) or isinstance(data, io.BufferedIOBase):
|
2016-06-06 17:51:35 +00:00
|
|
|
chunked = True
|
|
|
|
headers['content-type'] = 'application/octet-stream'
|
|
|
|
else:
|
|
|
|
data = json.dumps(data)
|
2016-04-14 10:22:10 +00:00
|
|
|
|
2016-06-06 17:51:35 +00:00
|
|
|
response = yield from self._session.request(method, url, headers=headers, data=data, auth=self._auth, chunked=chunked)
|
2016-03-18 15:55:54 +00:00
|
|
|
body = yield from response.read()
|
|
|
|
if body:
|
|
|
|
body = body.decode()
|
|
|
|
|
|
|
|
if response.status >= 300:
|
2016-06-07 14:06:37 +00:00
|
|
|
# Try to decode the GNS3 error
|
2016-06-07 17:38:01 +00:00
|
|
|
if body:
|
|
|
|
try:
|
|
|
|
msg = json.loads(body)["message"]
|
|
|
|
except (KeyError, json.decoder.JSONDecodeError):
|
|
|
|
msg = body
|
|
|
|
else:
|
|
|
|
msg = ""
|
2016-06-07 14:06:37 +00:00
|
|
|
|
2016-03-18 15:55:54 +00:00
|
|
|
if response.status == 400:
|
|
|
|
raise aiohttp.web.HTTPBadRequest(text="Bad request {} {}".format(url, body))
|
|
|
|
elif response.status == 401:
|
2016-04-15 15:57:06 +00:00
|
|
|
raise aiohttp.web.HTTPUnauthorized(text="Invalid authentication for compute {}".format(self.id))
|
2016-03-18 15:55:54 +00:00
|
|
|
elif response.status == 403:
|
2016-06-07 14:06:37 +00:00
|
|
|
raise aiohttp.web.HTTPForbidden(text=msg)
|
2016-03-18 15:55:54 +00:00
|
|
|
elif response.status == 404:
|
2016-06-07 14:06:37 +00:00
|
|
|
raise aiohttp.web.HTTPNotFound(text=msg)
|
2016-03-18 15:55:54 +00:00
|
|
|
elif response.status == 409:
|
2016-06-07 17:38:01 +00:00
|
|
|
try:
|
|
|
|
raise ComputeConflict(json.loads(body))
|
|
|
|
# If the 409 doesn't come from a GNS3 server
|
|
|
|
except json.decoder.JSONDecodeError:
|
|
|
|
raise aiohttp.web.HTTPConflict(text=msg)
|
2016-06-07 14:06:37 +00:00
|
|
|
elif response.status == 500:
|
|
|
|
raise aiohttp.web.HTTPInternalServerError(text="Internal server error {}".format(url))
|
2016-04-20 14:24:30 +00:00
|
|
|
elif response.status == 503:
|
|
|
|
raise aiohttp.web.HTTPServiceUnavailable(text="Service unavailable {} {}".format(url, body))
|
2016-03-18 15:55:54 +00:00
|
|
|
else:
|
|
|
|
raise NotImplementedError("{} status code is not supported".format(response.status))
|
|
|
|
if body and len(body):
|
|
|
|
try:
|
|
|
|
response.json = json.loads(body)
|
2016-05-11 21:19:00 +00:00
|
|
|
except ValueError:
|
2016-03-18 15:55:54 +00:00
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
|
2016-06-06 17:51:35 +00:00
|
|
|
else:
|
2016-03-18 15:55:54 +00:00
|
|
|
response.json = {}
|
|
|
|
return response
|
2016-03-10 09:32:07 +00:00
|
|
|
|
2016-04-14 10:22:10 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def get(self, path, **kwargs):
|
|
|
|
return (yield from self.http_query("GET", path, **kwargs))
|
2016-04-14 10:22:10 +00:00
|
|
|
|
2016-03-10 09:32:07 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def post(self, path, data={}, **kwargs):
|
|
|
|
response = yield from self.http_query("POST", path, data, **kwargs)
|
2016-04-14 10:22:10 +00:00
|
|
|
return response
|
2016-03-14 19:54:05 +00:00
|
|
|
|
2016-04-18 15:36:38 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def put(self, path, data={}, **kwargs):
|
|
|
|
response = yield from self.http_query("PUT", path, data, **kwargs)
|
2016-04-18 15:36:38 +00:00
|
|
|
return response
|
|
|
|
|
2016-03-14 19:54:05 +00:00
|
|
|
@asyncio.coroutine
|
2016-05-19 14:21:35 +00:00
|
|
|
def delete(self, path, **kwargs):
|
|
|
|
return (yield from self.http_query("DELETE", path, **kwargs))
|
2016-06-02 14:44:38 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
2016-06-06 13:45:32 +00:00
|
|
|
def forward(self, method, type, path, data=None):
|
2016-06-02 14:44:38 +00:00
|
|
|
"""
|
|
|
|
Forward a call to the emulator on compute
|
|
|
|
"""
|
2016-06-07 09:21:19 +00:00
|
|
|
res = yield from self.http_query(method, "/{}/{}".format(type, path), data=data, timeout=None)
|
2016-06-02 16:38:47 +00:00
|
|
|
return res.json
|
2016-06-08 12:14:03 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def images(self, type):
|
|
|
|
"""
|
|
|
|
Return the list of images available for this type on controller
|
|
|
|
and on the compute node.
|
|
|
|
"""
|
|
|
|
images = []
|
|
|
|
|
|
|
|
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=120)
|
|
|
|
images = res.json
|
|
|
|
|
2016-06-08 13:59:54 +00:00
|
|
|
if type in ["qemu", "dynamips", "iou"]:
|
|
|
|
for path in scan_for_images(type):
|
|
|
|
image = os.path.basename(path)
|
|
|
|
if image not in [i['filename'] for i in images]:
|
|
|
|
images.append({"filename": image, "path": image})
|
2016-06-08 12:14:03 +00:00
|
|
|
return images
|