gns3-server/gns3server/modules/project.py

252 lines
7.9 KiB
Python
Raw Normal View History

2015-01-19 17:23:41 +02:00
# -*- 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 aiohttp
2015-01-19 17:23:41 +02:00
import os
2015-01-23 12:28:58 +02:00
import shutil
2015-01-26 13:10:30 +02:00
import asyncio
from uuid import UUID, uuid4
2015-01-19 17:23:41 +02:00
2015-01-26 13:10:30 +02:00
from ..config import Config
from ..utils.asyncio import wait_run_in_executor
2015-01-19 17:23:41 +02:00
2015-01-23 19:37:29 +02:00
import logging
log = logging.getLogger(__name__)
2015-01-19 17:23:41 +02:00
class Project:
2015-01-31 23:34:49 +02:00
2015-01-19 17:23:41 +02:00
"""
A project contains a list of VM.
In theory VM are isolated project/project.
:param project_id: Force project identifier (None by default auto generate an UUID)
2015-01-19 17:23:41 +02:00
:param location: Parent path of the project. (None should create a tmp directory)
2015-01-23 17:02:26 +02:00
:param temporary: Boolean the project is a temporary project (destroy when closed)
2015-01-19 17:23:41 +02:00
"""
2015-01-19 23:43:35 +02:00
def __init__(self, project_id=None, location=None, temporary=False):
2015-01-19 23:43:35 +02:00
if project_id is None:
self._id = str(uuid4())
2015-01-19 17:23:41 +02:00
else:
try:
UUID(project_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="{} is not a valid UUID".format(project_id))
self._id = project_id
2015-01-19 17:23:41 +02:00
2015-01-23 18:39:17 +02:00
config = Config.instance().get_section_config("Server")
2015-01-19 23:43:35 +02:00
self._location = location
2015-01-19 17:23:41 +02:00
if location is None:
2015-01-23 18:39:17 +02:00
self._location = config.get("project_directory", self._get_default_project_directory())
else:
if config.get("local", False) is False:
raise aiohttp.web.HTTPForbidden(text="You are not allowed to modifiy the project directory location")
2015-01-19 17:23:41 +02:00
2015-01-23 15:07:10 +02:00
self._vms = set()
2015-01-23 12:28:58 +02:00
self._vms_to_destroy = set()
self._path = os.path.join(self._location, self._id)
try:
2015-01-22 00:21:15 +02:00
os.makedirs(os.path.join(self._path, "vms"), exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
self.temporary = temporary
log.debug("Create project {id} in directory {path}".format(path=self._path, id=self._id))
@classmethod
def _get_default_project_directory(cls):
2015-01-23 18:39:17 +02:00
"""
Return the default location for the project directory
depending of the operating system
"""
path = os.path.normpath(os.path.expanduser("~/GNS3/projects"))
try:
os.makedirs(path, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create project directory: {}".format(e))
return path
2015-01-19 23:43:35 +02:00
@property
def id(self):
2015-01-19 23:43:35 +02:00
return self._id
2015-01-19 17:23:41 +02:00
@property
def location(self):
return self._location
@property
def path(self):
return self._path
2015-01-23 15:07:10 +02:00
@property
def vms(self):
return self._vms
2015-01-23 17:13:58 +02:00
@property
def temporary(self):
return self._temporary
@temporary.setter
def temporary(self, temporary):
if hasattr(self, 'temporary') and temporary == self._temporary:
return
2015-01-23 17:13:58 +02:00
self._temporary = temporary
if self._temporary:
try:
with open(os.path.join(self._path, ".gns3_temporary"), 'w+') as f:
f.write("1")
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create temporary project: {}".format(e))
else:
if os.path.exists(os.path.join(self._path, ".gns3_temporary")):
os.remove(os.path.join(self._path, ".gns3_temporary"))
2015-01-23 12:28:58 +02:00
def vm_working_directory(self, vm):
"""
Return a working directory for a specific VM.
If the directory doesn't exist, the directory is created.
2015-01-23 12:28:58 +02:00
:param vm: An instance of VM
:returns: A string with a VM working directory
"""
workdir = os.path.join(self._path, vm.manager.module_name.lower(), vm.id)
try:
2015-01-22 04:28:52 +02:00
os.makedirs(workdir, exist_ok=True)
except OSError as e:
2015-01-24 03:33:49 +02:00
raise aiohttp.web.HTTPInternalServerError(text="Could not create the VM working directory: {}".format(e))
return workdir
def capture_working_directory(self):
"""
Return a working directory where to store packet capture files.
:returns: path to the directory
"""
workdir = os.path.join(self._path, "captures")
try:
os.makedirs(workdir, exist_ok=True)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not create the capture working directory: {}".format(e))
2015-01-22 04:28:52 +02:00
return workdir
2015-01-23 12:28:58 +02:00
def mark_vm_for_destruction(self, vm):
"""
:param vm: An instance of VM
"""
self.remove_vm(vm)
2015-01-23 12:28:58 +02:00
self._vms_to_destroy.add(vm)
2015-01-19 17:23:41 +02:00
def __json__(self):
2015-01-19 23:43:35 +02:00
2015-01-19 17:23:41 +02:00
return {
"project_id": self._id,
2015-01-23 17:02:26 +02:00
"location": self._location,
"temporary": self._temporary
2015-01-19 17:23:41 +02:00
}
2015-01-23 12:28:58 +02:00
2015-01-23 15:07:10 +02:00
def add_vm(self, vm):
"""
Add a VM to the project.
In theory this should be called by the VM manager.
2015-01-23 15:07:10 +02:00
2015-01-23 17:02:26 +02:00
:param vm: A VM instance
2015-01-23 15:07:10 +02:00
"""
self._vms.add(vm)
def remove_vm(self, vm):
"""
Remove a VM from the project.
In theory this should be called by the VM manager.
2015-01-23 17:02:26 +02:00
:param vm: A VM instance
"""
if vm in self._vms:
self._vms.remove(vm)
2015-01-26 13:10:30 +02:00
@asyncio.coroutine
2015-01-23 12:48:20 +02:00
def close(self):
"""Close the project, but keep information on disk"""
2015-01-23 12:48:20 +02:00
2015-01-26 13:10:30 +02:00
yield from self._close_and_clean(self._temporary)
2015-01-23 17:02:26 +02:00
2015-01-26 13:10:30 +02:00
@asyncio.coroutine
2015-01-23 17:02:26 +02:00
def _close_and_clean(self, cleanup):
"""
Close the project, and cleanup the disk if cleanup is True
:param cleanup: If True drop the project directory
"""
2015-01-23 15:07:10 +02:00
for vm in self._vms:
if asyncio.iscoroutinefunction(vm.close):
yield from vm.close()
else:
vm.close()
2015-01-23 17:02:26 +02:00
if cleanup and os.path.exists(self.path):
2015-01-26 14:54:44 +02:00
try:
yield from wait_run_in_executor(shutil.rmtree, self.path)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the project directory: {}".format(e))
2015-01-23 12:48:20 +02:00
2015-01-26 13:10:30 +02:00
@asyncio.coroutine
2015-01-23 12:28:58 +02:00
def commit(self):
"""Write project changes on disk"""
2015-01-23 12:48:20 +02:00
2015-01-23 12:28:58 +02:00
while self._vms_to_destroy:
vm = self._vms_to_destroy.pop()
directory = self.vm_working_directory(vm)
if os.path.exists(directory):
2015-01-26 14:54:44 +02:00
try:
yield from wait_run_in_executor(shutil.rmtree, directory)
except OSError as e:
raise aiohttp.web.HTTPInternalServerError(text="Could not delete the project directory: {}".format(e))
self.remove_vm(vm)
2015-01-23 12:48:20 +02:00
2015-01-26 13:10:30 +02:00
@asyncio.coroutine
2015-01-23 12:48:20 +02:00
def delete(self):
"""Remove project from disk"""
2015-01-26 13:10:30 +02:00
yield from self._close_and_clean(True)
@classmethod
def clean_project_directory(cls):
"""At startup drop old temporary project. After a crash for example"""
config = Config.instance().get_section_config("Server")
directory = config.get("project_directory", cls._get_default_project_directory())
if os.path.exists(directory):
for project in os.listdir(directory):
path = os.path.join(directory, project)
if os.path.exists(os.path.join(path, ".gns3_temporary")):
log.warning("Purge old temporary project {}".format(project))
shutil.rmtree(path)