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-08-25 17:14:29 +00:00
|
|
|
import ipaddress
|
2016-03-10 09:32:07 +00:00
|
|
|
import aiohttp
|
|
|
|
import asyncio
|
2016-08-22 16:49:25 +00:00
|
|
|
import socket
|
2016-03-10 09:32:07 +00:00
|
|
|
import json
|
2016-05-25 12:10:03 +00:00
|
|
|
import uuid
|
2016-08-30 07:58:37 +00:00
|
|
|
import sys
|
2016-06-07 17:38:01 +00:00
|
|
|
import io
|
2017-05-05 18:09:51 +00:00
|
|
|
from operator import itemgetter
|
2016-03-03 15:02:27 +00:00
|
|
|
|
2016-05-14 00:48:10 +00:00
|
|
|
from ..utils import parse_version
|
2017-02-06 09:49:09 +00:00
|
|
|
from ..utils.images import list_images
|
2016-11-21 08:58:42 +00:00
|
|
|
from ..utils.asyncio import locked_coroutine
|
2016-03-04 15:11:31 +00:00
|
|
|
from ..controller.controller_error import ControllerError
|
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-10-26 12:43:47 +00:00
|
|
|
def __init__(self, compute_id, controller=None, protocol="http", host="localhost", port=3080, user=None, password=None, name=None, console_host=None):
|
2016-07-22 09:43:14 +00:00
|
|
|
self._http_session = 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
|
2016-10-26 16:32:01 +00:00
|
|
|
self._console_host = console_host
|
2016-05-25 09:27:41 +00:00
|
|
|
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-08-29 15:36:24 +00:00
|
|
|
self._closed = False # Close mean we are destroying the compute node
|
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-06-30 07:45:11 +00:00
|
|
|
self._cpu_usage_percent = None
|
|
|
|
self._memory_usage_percent = None
|
2016-08-29 13:53:10 +00:00
|
|
|
self._capabilities = {
|
|
|
|
"version": None,
|
|
|
|
"node_types": []
|
|
|
|
}
|
2016-05-23 09:20:52 +00:00
|
|
|
self.name = name
|
2016-06-08 15:18:40 +00:00
|
|
|
# Websocket for notifications
|
|
|
|
self._ws = None
|
2016-03-03 15:02:27 +00:00
|
|
|
|
2016-08-25 17:14:29 +00:00
|
|
|
# Cache of interfaces on remote host
|
|
|
|
self._interfaces_cache = None
|
|
|
|
|
2016-12-15 20:57:59 +00:00
|
|
|
self._connection_failure = 0
|
|
|
|
|
2016-07-20 10:43:23 +00:00
|
|
|
def _session(self):
|
|
|
|
if self._http_session is None or self._http_session.closed is True:
|
2016-11-16 14:04:10 +00:00
|
|
|
self._http_session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=None, force_close=True))
|
2016-07-20 10:43:23 +00:00
|
|
|
return self._http_session
|
|
|
|
|
2016-03-18 15:55:54 +00:00
|
|
|
def __del__(self):
|
2016-07-20 10:43:23 +00:00
|
|
|
if self._http_session:
|
|
|
|
self._http_session.close()
|
2016-03-18 15:55:54 +00:00
|
|
|
|
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()
|
2017-03-23 14:50:02 +00:00
|
|
|
self._auth = aiohttp.BasicAuth(self._user, self._password, "utf-8")
|
2016-05-26 11:32:52 +00:00
|
|
|
else:
|
|
|
|
self._password = None
|
|
|
|
self._auth = aiohttp.BasicAuth(self._user, "")
|
2016-03-16 14:55:07 +00:00
|
|
|
|
2016-08-25 17:14:29 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def interfaces(self):
|
|
|
|
"""
|
|
|
|
Get the list of network on compute
|
|
|
|
"""
|
|
|
|
if not self._interfaces_cache:
|
|
|
|
response = yield from self.get("/network/interfaces")
|
|
|
|
self._interfaces_cache = response.json
|
|
|
|
return self._interfaces_cache
|
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def update(self, **kwargs):
|
|
|
|
for kw in kwargs:
|
2016-10-27 14:54:05 +00:00
|
|
|
if kw not in ("user", "password"):
|
|
|
|
setattr(self, kw, kwargs[kw])
|
|
|
|
# It's important to set user and password at the same time
|
|
|
|
if "user" in kwargs or "password" in kwargs:
|
|
|
|
self._set_auth(kwargs.get("user", self._user), kwargs.get("password", self._password))
|
2016-07-20 10:43:23 +00:00
|
|
|
if self._http_session:
|
|
|
|
self._http_session.close()
|
2016-05-25 09:27:41 +00:00
|
|
|
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
|
2016-07-20 10:43:23 +00:00
|
|
|
if self._http_session:
|
|
|
|
self._http_session.close()
|
2016-06-08 15:18:40 +00:00
|
|
|
if self._ws:
|
|
|
|
yield from self._ws.close()
|
|
|
|
self._ws = None
|
2016-08-29 15:36:24 +00:00
|
|
|
self._closed = True
|
2016-06-02 11:44:12 +00:00
|
|
|
|
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
|
|
|
|
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-08-25 17:14:29 +00:00
|
|
|
@property
|
|
|
|
def host_ip(self):
|
|
|
|
"""
|
|
|
|
Return the IP associated to the host
|
|
|
|
"""
|
2017-02-06 15:47:40 +00:00
|
|
|
try:
|
|
|
|
return socket.gethostbyname(self._host)
|
|
|
|
except socket.gaierror:
|
|
|
|
return '0.0.0.0'
|
2016-08-25 17:14:29 +00:00
|
|
|
|
2016-05-25 09:27:41 +00:00
|
|
|
@host.setter
|
|
|
|
def host(self, host):
|
|
|
|
self._host = host
|
2016-10-26 16:32:01 +00:00
|
|
|
if self._console_host is None:
|
|
|
|
self._console_host = host
|
2016-05-25 09:27:41 +00:00
|
|
|
|
2016-10-26 12:43:47 +00:00
|
|
|
@property
|
|
|
|
def console_host(self):
|
|
|
|
return self._console_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-06-30 07:45:11 +00:00
|
|
|
@property
|
|
|
|
def cpu_usage_percent(self):
|
|
|
|
return self._cpu_usage_percent
|
|
|
|
|
|
|
|
@property
|
|
|
|
def memory_usage_percent(self):
|
|
|
|
return self._memory_usage_percent
|
|
|
|
|
2016-06-15 13:12:38 +00:00
|
|
|
def __json__(self, topology_dump=False):
|
|
|
|
"""
|
|
|
|
:param topology_dump: Filter to keep only properties require for saving on disk
|
|
|
|
"""
|
|
|
|
if topology_dump:
|
|
|
|
return {
|
|
|
|
"compute_id": self._id,
|
|
|
|
"name": self._name,
|
|
|
|
"protocol": self._protocol,
|
|
|
|
"host": self._host,
|
2016-06-15 16:22:11 +00:00
|
|
|
"port": self._port
|
2016-06-15 13:12:38 +00:00
|
|
|
}
|
2016-03-03 15:02:27 +00:00
|
|
|
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-06-30 07:45:11 +00:00
|
|
|
"connected": self._connected,
|
|
|
|
"cpu_usage_percent": self._cpu_usage_percent,
|
2016-08-29 13:53:10 +00:00
|
|
|
"memory_usage_percent": self._memory_usage_percent,
|
|
|
|
"capabilities": self._capabilities
|
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-07-21 18:17:36 +00:00
|
|
|
def download_file(self, project, path):
|
|
|
|
"""
|
|
|
|
Read file of a project and download it
|
|
|
|
|
|
|
|
:param project: A project object
|
|
|
|
:param path: The path of the file in the project
|
|
|
|
:returns: A file stream
|
|
|
|
"""
|
|
|
|
|
|
|
|
url = self._getUrl("/projects/{}/files/{}".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))
|
2016-09-19 14:51:15 +00:00
|
|
|
return response
|
2016-07-21 18:17:36 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def stream_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
|
|
|
|
"""
|
|
|
|
|
2016-08-19 09:05:54 +00:00
|
|
|
# Due to Python 3.4 limitation we can't use with and asyncio
|
|
|
|
# https://www.python.org/dev/peps/pep-0492/
|
|
|
|
# that why we wrap the answer
|
|
|
|
class StreamResponse:
|
2016-08-19 09:20:56 +00:00
|
|
|
|
2016-08-19 09:05:54 +00:00
|
|
|
def __init__(self, response):
|
|
|
|
self._response = response
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self._response.content
|
|
|
|
|
|
|
|
def __exit__(self):
|
|
|
|
self._response.close()
|
|
|
|
|
2016-04-22 14:22:03 +00:00
|
|
|
url = self._getUrl("/projects/{}/stream/{}".format(project.id, path))
|
2017-01-16 19:29:45 +00:00
|
|
|
response = yield from self._session().request("GET", url, auth=self._auth, timeout=None)
|
2016-04-22 14:22:03 +00:00
|
|
|
if response.status == 404:
|
|
|
|
raise aiohttp.web.HTTPNotFound(text="{} not found on compute".format(path))
|
2016-08-19 09:05:54 +00:00
|
|
|
return StreamResponse(response)
|
2016-04-22 14:22:03 +00:00
|
|
|
|
2016-03-10 09:32:07 +00:00
|
|
|
@asyncio.coroutine
|
2016-12-15 20:57:59 +00:00
|
|
|
def http_query(self, method, path, data=None, dont_connect=False, **kwargs):
|
|
|
|
"""
|
|
|
|
:param dont_connect: If true do not reconnect if not connected
|
|
|
|
"""
|
|
|
|
if not self._connected and not dont_connect:
|
2016-09-01 13:36:41 +00:00
|
|
|
if self._id == "vm" and not self._controller.gns3vm.running:
|
|
|
|
yield from self._controller.gns3vm.start()
|
|
|
|
|
2016-08-29 13:53:10 +00:00
|
|
|
yield from self.connect()
|
2016-12-15 20:57:59 +00:00
|
|
|
if not self._connected and not dont_connect:
|
|
|
|
raise ComputeError("Can't connect to {}".format(self._name))
|
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
|
|
|
|
2017-02-06 16:56:08 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def _try_reconnect(self):
|
|
|
|
"""
|
|
|
|
We catch error during reconnect
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
yield from self.connect()
|
|
|
|
except aiohttp.web.HTTPConflict:
|
|
|
|
pass
|
|
|
|
|
2016-11-21 08:58:42 +00:00
|
|
|
@locked_coroutine
|
2016-08-29 13:53:10 +00:00
|
|
|
def connect(self):
|
2016-03-18 15:55:54 +00:00
|
|
|
"""
|
|
|
|
Check if remote server is accessible
|
|
|
|
"""
|
2016-08-29 15:36:24 +00:00
|
|
|
if not self._connected and not self._closed:
|
2016-08-29 13:53:10 +00:00
|
|
|
try:
|
|
|
|
response = yield from self._run_http_query("GET", "/capabilities")
|
2016-11-11 09:38:59 +00:00
|
|
|
except ComputeError:
|
2016-08-30 07:58:37 +00:00
|
|
|
# Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
|
|
|
|
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
|
2016-12-15 20:57:59 +00:00
|
|
|
self._connection_failure += 1
|
|
|
|
# After 5 failure we close the project using the compute to avoid sync issues
|
|
|
|
if self._connection_failure == 5:
|
2017-02-06 16:56:08 +00:00
|
|
|
log.warning("Can't connect to compute %s", self._id)
|
2016-12-15 20:57:59 +00:00
|
|
|
yield from self._controller.close_compute_projects(self)
|
2017-02-06 16:56:08 +00:00
|
|
|
|
|
|
|
asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
|
2016-12-15 20:57:59 +00:00
|
|
|
|
2016-08-29 13:53:10 +00:00
|
|
|
return
|
2016-11-15 17:28:32 +00:00
|
|
|
except aiohttp.web.HTTPNotFound:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
|
2016-12-12 10:27:18 +00:00
|
|
|
except aiohttp.web.HTTPUnauthorized:
|
2017-02-06 09:49:09 +00:00
|
|
|
raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
|
|
|
|
except aiohttp.web.HTTPServiceUnavailable:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
|
2017-03-13 15:59:42 +00:00
|
|
|
except ValueError:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))
|
2016-04-20 14:24:30 +00:00
|
|
|
|
2016-03-16 14:55:07 +00:00
|
|
|
if "version" not in response.json:
|
2016-07-21 13:10:11 +00:00
|
|
|
self._http_session.close()
|
2016-03-16 14:55:07 +00:00
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
|
2016-08-29 13:53:10 +00:00
|
|
|
self._capabilities = response.json
|
2016-03-16 14:55:07 +00:00
|
|
|
if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
|
2016-07-21 13:10:11 +00:00
|
|
|
self._http_session.close()
|
2016-03-16 14:55:07 +00:00
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))
|
|
|
|
|
2016-07-21 13:10:11 +00:00
|
|
|
self._notifications = asyncio.gather(self._connect_notification())
|
2016-03-18 15:55:54 +00:00
|
|
|
self._connected = True
|
2016-12-15 20:57:59 +00:00
|
|
|
self._connection_failure = 0
|
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-08-31 07:59:50 +00:00
|
|
|
try:
|
2016-08-31 13:19:53 +00:00
|
|
|
self._ws = yield from self._session().ws_connect(self._getUrl("/notifications/ws"), auth=self._auth)
|
2017-05-16 17:28:47 +00:00
|
|
|
except (aiohttp.WSServerHandshakeError, aiohttp.ClientResponseError):
|
2016-09-02 12:09:01 +00:00
|
|
|
self._ws = None
|
2016-08-31 07:59:50 +00:00
|
|
|
while self._ws is not None:
|
2016-08-19 09:20:56 +00:00
|
|
|
try:
|
|
|
|
response = yield from self._ws.receive()
|
2017-05-16 17:28:47 +00:00
|
|
|
except aiohttp.WSServerHandshakeError:
|
2016-08-19 09:20:56 +00:00
|
|
|
self._ws = None
|
2016-08-29 15:36:24 +00:00
|
|
|
break
|
2017-05-16 17:28:47 +00:00
|
|
|
if response.tp == aiohttp.WSMsgType.closed or response.tp == aiohttp.WSMsgType.error or response.data is None:
|
2016-03-18 15:55:54 +00:00
|
|
|
self._connected = False
|
|
|
|
break
|
|
|
|
msg = json.loads(response.data)
|
|
|
|
action = msg.pop("action")
|
|
|
|
event = msg.pop("event")
|
2016-06-30 07:45:11 +00:00
|
|
|
|
|
|
|
if action == "ping":
|
|
|
|
self._cpu_usage_percent = event["cpu_usage_percent"]
|
|
|
|
self._memory_usage_percent = event["memory_usage_percent"]
|
|
|
|
self._controller.notification.emit("compute.updated", self.__json__())
|
|
|
|
else:
|
2016-11-22 15:05:00 +00:00
|
|
|
yield from self._controller.notification.dispatch(action, event, compute_id=self.id)
|
2016-08-29 15:36:24 +00:00
|
|
|
if self._ws:
|
|
|
|
yield from self._ws.close()
|
|
|
|
|
2016-08-30 07:58:37 +00:00
|
|
|
# Try to reconnect after 1 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
|
|
|
|
if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
|
|
|
|
asyncio.get_event_loop().call_later(1, lambda: asyncio.async(self.connect()))
|
2016-06-08 15:18:40 +00:00
|
|
|
self._ws = None
|
2016-08-29 15:36:24 +00:00
|
|
|
self._cpu_usage_percent = None
|
|
|
|
self._memory_usage_percent = None
|
|
|
|
self._controller.notification.emit("compute.updated", self.__json__())
|
2016-03-18 15:55:54 +00:00
|
|
|
|
|
|
|
def _getUrl(self, path):
|
2016-10-17 12:10:25 +00:00
|
|
|
host = self._host
|
|
|
|
# IPV6
|
2016-10-17 16:20:29 +00:00
|
|
|
if host:
|
|
|
|
# IPV6
|
|
|
|
if ":" in host:
|
|
|
|
# Reduce IPV6 to his simple form
|
|
|
|
host = str(ipaddress.IPv6Address(host))
|
|
|
|
if host == "::":
|
|
|
|
host = "::1"
|
|
|
|
host = "[{}]".format(host)
|
|
|
|
elif host == "0.0.0.0":
|
|
|
|
host = "127.0.0.1"
|
2016-10-17 12:10:25 +00:00
|
|
|
return "{}://{}:{}/v2/compute{}".format(self._protocol, host, self._port, path)
|
2016-03-16 14:55:07 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
2016-11-07 16:34:51 +00:00
|
|
|
def _run_http_query(self, method, path, data=None, timeout=20, raw=False):
|
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'
|
2017-05-16 17:28:47 +00:00
|
|
|
chunked = None
|
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__())
|
2016-12-15 16:12:54 +00:00
|
|
|
elif isinstance(data, aiohttp.streams.EmptyStreamReader):
|
|
|
|
data = None
|
2016-06-06 17:51:35 +00:00
|
|
|
# Stream the request
|
2016-10-04 08:56:38 +00:00
|
|
|
elif isinstance(data, aiohttp.streams.StreamReader) or isinstance(data, bytes):
|
2016-06-06 17:51:35 +00:00
|
|
|
chunked = True
|
|
|
|
headers['content-type'] = 'application/octet-stream'
|
2016-10-04 08:56:38 +00:00
|
|
|
# If the data is an open file we will iterate on it
|
|
|
|
elif isinstance(data, io.BufferedIOBase):
|
|
|
|
chunked = True
|
|
|
|
headers['content-type'] = 'application/octet-stream'
|
|
|
|
|
|
|
|
def send_data(f):
|
|
|
|
while True:
|
2016-10-20 15:24:05 +00:00
|
|
|
chunk = f.read(4096)
|
2016-10-04 08:56:38 +00:00
|
|
|
if not chunk:
|
|
|
|
break
|
|
|
|
yield chunk
|
|
|
|
|
|
|
|
data = send_data(data)
|
2016-06-06 17:51:35 +00:00
|
|
|
else:
|
2017-05-16 17:28:47 +00:00
|
|
|
data = json.dumps(data).encode("utf-8")
|
2016-11-11 09:38:59 +00:00
|
|
|
try:
|
|
|
|
response = yield from self._session().request(method, url, headers=headers, data=data, auth=self._auth, chunked=chunked, timeout=timeout)
|
2016-11-21 08:58:42 +00:00
|
|
|
except asyncio.TimeoutError as e:
|
|
|
|
raise ComputeError("Timeout error when connecting to {}".format(url))
|
2017-05-16 17:28:47 +00:00
|
|
|
except (aiohttp.ClientError, aiohttp.ServerDisconnectedError, ValueError) as e:
|
2016-11-11 09:38:59 +00:00
|
|
|
raise ComputeError(str(e))
|
2016-07-11 07:33:55 +00:00
|
|
|
body = yield from response.read()
|
2016-07-27 16:31:02 +00:00
|
|
|
if body and not raw:
|
2016-07-11 07:33:55 +00:00
|
|
|
body = body.decode()
|
|
|
|
|
|
|
|
if response.status >= 300:
|
|
|
|
# Try to decode the GNS3 error
|
2016-07-27 16:31:02 +00:00
|
|
|
if body and not raw:
|
2016-03-18 15:55:54 +00:00
|
|
|
try:
|
2016-07-11 07:33:55 +00:00
|
|
|
msg = json.loads(body)["message"]
|
|
|
|
except (KeyError, ValueError):
|
|
|
|
msg = body
|
|
|
|
else:
|
|
|
|
msg = ""
|
|
|
|
|
|
|
|
if response.status == 400:
|
|
|
|
raise aiohttp.web.HTTPBadRequest(text="Bad request {} {}".format(url, body))
|
|
|
|
elif response.status == 401:
|
|
|
|
raise aiohttp.web.HTTPUnauthorized(text="Invalid authentication for compute {}".format(self.id))
|
|
|
|
elif response.status == 403:
|
|
|
|
raise aiohttp.web.HTTPForbidden(text=msg)
|
|
|
|
elif response.status == 404:
|
2016-09-05 14:55:38 +00:00
|
|
|
raise aiohttp.web.HTTPNotFound(text="{} {} not found".format(method, path))
|
2017-05-16 06:36:54 +00:00
|
|
|
elif response.status == 408 or response.status == 504:
|
2016-10-27 13:32:07 +00:00
|
|
|
raise aiohttp.web.HTTPRequestTimeout(text="{} {} request timeout".format(method, path))
|
2016-07-11 07:33:55 +00:00
|
|
|
elif response.status == 409:
|
|
|
|
try:
|
|
|
|
raise ComputeConflict(json.loads(body))
|
|
|
|
# If the 409 doesn't come from a GNS3 server
|
2016-05-11 21:19:00 +00:00
|
|
|
except ValueError:
|
2016-07-11 07:33:55 +00:00
|
|
|
raise aiohttp.web.HTTPConflict(text=msg)
|
|
|
|
elif response.status == 500:
|
|
|
|
raise aiohttp.web.HTTPInternalServerError(text="Internal server error {}".format(url))
|
|
|
|
elif response.status == 503:
|
|
|
|
raise aiohttp.web.HTTPServiceUnavailable(text="Service unavailable {} {}".format(url, body))
|
2016-06-06 17:51:35 +00:00
|
|
|
else:
|
2016-07-11 07:33:55 +00:00
|
|
|
raise NotImplementedError("{} status code is not supported".format(response.status))
|
|
|
|
if body and len(body):
|
2016-07-27 16:31:02 +00:00
|
|
|
if raw:
|
|
|
|
response.body = body
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
response.json = json.loads(body)
|
|
|
|
except ValueError:
|
|
|
|
raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
|
2016-07-11 07:33:55 +00:00
|
|
|
else:
|
|
|
|
response.json = {}
|
2016-07-27 16:31:02 +00:00
|
|
|
response.body = b""
|
2016-07-11 07:33:55 +00:00
|
|
|
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-11-02 10:06:45 +00:00
|
|
|
try:
|
2017-05-22 11:57:32 +00:00
|
|
|
action = "/{}/{}".format(type, path)
|
|
|
|
res = yield from self.http_query(method, action, data=data, timeout=None)
|
2017-05-16 17:28:47 +00:00
|
|
|
except aiohttp.ServerDisconnectedError:
|
2017-05-22 11:57:32 +00:00
|
|
|
log.error("Connection lost to %s during %s %s", self._id, method, action)
|
2016-11-02 10:06:45 +00:00
|
|
|
raise aiohttp.web.HTTPGatewayTimeout()
|
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 = []
|
|
|
|
|
2016-10-27 13:34:17 +00:00
|
|
|
res = yield from self.http_query("GET", "/{}/images".format(type), timeout=None)
|
2016-06-08 12:14:03 +00:00
|
|
|
images = res.json
|
|
|
|
|
2016-12-12 09:13:29 +00:00
|
|
|
try:
|
|
|
|
if type in ["qemu", "dynamips", "iou"]:
|
|
|
|
for local_image in list_images(type):
|
|
|
|
if local_image['filename'] not in [i['filename'] for i in images]:
|
|
|
|
images.append(local_image)
|
2017-05-09 10:25:15 +00:00
|
|
|
images = sorted(images, key=itemgetter('filename'))
|
|
|
|
else:
|
|
|
|
images = sorted(images, key=itemgetter('image'))
|
2016-12-12 09:13:29 +00:00
|
|
|
except OSError as e:
|
|
|
|
raise ComputeError("Can't list images: {}".format(str(e)))
|
2016-06-08 12:14:03 +00:00
|
|
|
return images
|
2016-07-21 18:17:36 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def list_files(self, project):
|
|
|
|
"""
|
|
|
|
List files in the project on computes
|
|
|
|
"""
|
|
|
|
path = "/projects/{}/files".format(project.id)
|
|
|
|
res = yield from self.http_query("GET", path, timeout=120)
|
|
|
|
return res.json
|
2016-08-25 17:14:29 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def get_ip_on_same_subnet(self, other_compute):
|
|
|
|
"""
|
|
|
|
Try to found the best ip for communication from one compute
|
|
|
|
to another
|
|
|
|
|
|
|
|
:returns: Tuple (ip_for_this_compute, ip_for_other_compute)
|
|
|
|
"""
|
|
|
|
if other_compute == self:
|
|
|
|
return (self.host_ip, self.host_ip)
|
|
|
|
|
2016-12-13 15:46:09 +00:00
|
|
|
# Perhaps the user has correct network gateway, we trust him
|
|
|
|
if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
|
|
|
|
return (self.host_ip, other_compute.host_ip)
|
|
|
|
|
2016-08-25 17:14:29 +00:00
|
|
|
this_compute_interfaces = yield from self.interfaces()
|
|
|
|
other_compute_interfaces = yield from other_compute.interfaces()
|
|
|
|
|
|
|
|
# Sort interface to put the compute host in first position
|
|
|
|
# we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
|
|
|
|
this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
|
|
|
|
other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)
|
|
|
|
|
|
|
|
for this_interface in this_compute_interfaces:
|
2016-09-05 16:02:49 +00:00
|
|
|
# Skip if no ip or no netmask (vbox when stopped set a null netmask)
|
|
|
|
if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
|
2016-08-25 17:14:29 +00:00
|
|
|
continue
|
2016-11-10 13:46:25 +00:00
|
|
|
# Ignore 169.254 network because it's for Windows special purpose
|
|
|
|
if this_interface["ip_address"].startswith("169.254."):
|
|
|
|
continue
|
2016-08-25 17:14:29 +00:00
|
|
|
|
|
|
|
this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)
|
|
|
|
|
|
|
|
for other_interface in other_compute_interfaces:
|
2016-11-11 15:08:52 +00:00
|
|
|
if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
|
2016-08-25 17:14:29 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
# Avoid stuff like 127.0.0.1
|
|
|
|
if other_interface["ip_address"] == this_interface["ip_address"]:
|
|
|
|
continue
|
|
|
|
|
|
|
|
other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
|
|
|
|
if this_network.overlaps(other_network):
|
|
|
|
return (this_interface["ip_address"], other_interface["ip_address"])
|
2016-11-10 21:39:16 +00:00
|
|
|
|
2016-08-25 17:14:29 +00:00
|
|
|
raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
|
2017-07-07 15:50:40 +00:00
|
|
|
|