mirror of https://github.com/GNS3/gns3-server
parent
814fd1fcfb
commit
68eca6c111
@ -0,0 +1,93 @@
|
||||
#!/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/>.
|
||||
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import shutil
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
from .import_project import import_project
|
||||
|
||||
|
||||
# The string use to extract the date from the filename
|
||||
FILENAME_TIME_FORMAT = "%d%m%y_%H%M%S"
|
||||
|
||||
|
||||
class Snapshot:
|
||||
"""
|
||||
A snapshot object
|
||||
"""
|
||||
|
||||
def __init__(self, project, name=None, filename=None):
|
||||
|
||||
assert filename or name, "You need to pass a name or a filename"
|
||||
|
||||
self._id = str(uuid.uuid4()) # We don't need to keep id between project loading because they are use only as key for operation like delete, update.. but have no impact on disk
|
||||
self._project = project
|
||||
if name:
|
||||
self._name = name
|
||||
self._created_at = datetime.now().timestamp()
|
||||
filename = self._name + "_" + datetime.utcfromtimestamp(self._created_at).replace(tzinfo=None).strftime(FILENAME_TIME_FORMAT) + ".gns3project"
|
||||
else:
|
||||
self._name = filename.split("_")[0]
|
||||
datestring = filename.replace(self._name + "_", "").split(".")[0]
|
||||
try:
|
||||
self._created_at = datetime.strptime(datestring, FILENAME_TIME_FORMAT).replace(tzinfo=timezone.utc).timestamp()
|
||||
except ValueError:
|
||||
self._created_at = datetime.utcnow().timestamp()
|
||||
self._path = os.path.join(project.path, "snapshots", filename)
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return self._id
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
return self._path
|
||||
|
||||
@property
|
||||
def created_at(self):
|
||||
return int(self._created_at)
|
||||
|
||||
@asyncio.coroutine
|
||||
def restore(self):
|
||||
"""
|
||||
Restore the snapshot
|
||||
"""
|
||||
|
||||
yield from self._project.delete_on_computes()
|
||||
yield from self._project.close()
|
||||
shutil.rmtree(os.path.join(self._project.path, "project-files"))
|
||||
with open(self._path, "rb") as f:
|
||||
project = yield from import_project(self._project.controller, self._project.id, f, location=self._project.path)
|
||||
yield from project.open()
|
||||
return project
|
||||
|
||||
def __json__(self):
|
||||
return {
|
||||
"snapshot_id": self._id,
|
||||
"name": self._name,
|
||||
"created_at": int(self._created_at),
|
||||
"project_id": self._project.id
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
#!/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/>.
|
||||
|
||||
|
||||
import logging
|
||||
log = logging.getLogger()
|
||||
|
||||
from gns3server.web.route import Route
|
||||
from gns3server.controller import Controller
|
||||
|
||||
from gns3server.schemas.snapshot import (
|
||||
SNAPSHOT_OBJECT_SCHEMA,
|
||||
SNAPSHOT_CREATE_SCHEMA
|
||||
)
|
||||
from gns3server.schemas.project import PROJECT_OBJECT_SCHEMA
|
||||
|
||||
|
||||
class SnapshotHandler:
|
||||
|
||||
@Route.post(
|
||||
r"/projects/{project_id}/snapshots",
|
||||
description="Create snapshot of a project",
|
||||
parameters={
|
||||
"project_id": "Project UUID",
|
||||
},
|
||||
input=SNAPSHOT_CREATE_SCHEMA,
|
||||
output=SNAPSHOT_OBJECT_SCHEMA,
|
||||
status_codes={
|
||||
201: "Snasphot created",
|
||||
404: "The project doesn't exist"
|
||||
})
|
||||
def create(request, response):
|
||||
controller = Controller.instance()
|
||||
project = controller.get_project(request.match_info["project_id"])
|
||||
snapshot = yield from project.snapshot(request.json["name"])
|
||||
response.json(snapshot)
|
||||
response.set_status(201)
|
||||
|
||||
@Route.get(
|
||||
r"/projects/{project_id}/snapshots",
|
||||
description="List snapshots of a project",
|
||||
parameters={
|
||||
"project_id": "Project UUID",
|
||||
},
|
||||
status_codes={
|
||||
200: "Snasphot list returned",
|
||||
404: "The project doesn't exist"
|
||||
})
|
||||
def list(request, response):
|
||||
controller = Controller.instance()
|
||||
project = controller.get_project(request.match_info["project_id"])
|
||||
snapshots = [s for s in project.snapshots.values()]
|
||||
response.json(sorted(snapshots, key=lambda s: s.created_at))
|
||||
|
||||
@Route.delete(
|
||||
r"/projects/{project_id}/snapshots/{snapshot_id}",
|
||||
description="Delete a snapshot from disk",
|
||||
parameters={
|
||||
"project_id": "Project UUID",
|
||||
"snapshot_id": "Snasphot UUID"
|
||||
},
|
||||
status_codes={
|
||||
204: "Changes have been written on disk",
|
||||
404: "The project or snapshot doesn't exist"
|
||||
})
|
||||
def delete(request, response):
|
||||
|
||||
controller = Controller.instance()
|
||||
project = controller.get_project(request.match_info["project_id"])
|
||||
yield from project.delete_snapshot(request.match_info["snapshot_id"])
|
||||
response.set_status(204)
|
||||
|
||||
@Route.post(
|
||||
r"/projects/{project_id}/snapshots/{snapshot_id}/restore",
|
||||
description="Restore a snapshot from disk",
|
||||
parameters={
|
||||
"project_id": "Project UUID",
|
||||
"snapshot_id": "Snasphot UUID"
|
||||
},
|
||||
output=PROJECT_OBJECT_SCHEMA,
|
||||
status_codes={
|
||||
201: "The snapshot has been restored",
|
||||
404: "The project or snapshot doesn't exist"
|
||||
})
|
||||
def restore(request, response):
|
||||
|
||||
controller = Controller.instance()
|
||||
project = controller.get_project(request.match_info["project_id"])
|
||||
snapshot = project.get_snapshot(request.match_info["snapshot_id"])
|
||||
project = yield from snapshot.restore()
|
||||
response.set_status(201)
|
||||
response.json(project)
|
@ -0,0 +1,64 @@
|
||||
# -*- 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/>.
|
||||
|
||||
|
||||
SNAPSHOT_CREATE_SCHEMA = {
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"description": "Request validation to create a new snapshot",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"description": "Snapshot name",
|
||||
"minLength": 1
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
"required": ["name"]
|
||||
}
|
||||
|
||||
SNAPSHOT_OBJECT_SCHEMA = {
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"description": "Request validation to update a Project instance",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"snapshot_id": {
|
||||
"description": "Snapshot UUID",
|
||||
"type": "string",
|
||||
"minLength": 36,
|
||||
"maxLength": 36,
|
||||
"pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
|
||||
},
|
||||
"project_id": {
|
||||
"description": "Project UUID",
|
||||
"type": "string",
|
||||
"minLength": 36,
|
||||
"maxLength": 36,
|
||||
"pattern": "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$"
|
||||
},
|
||||
"name": {
|
||||
"description": "Project name",
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"created_at": {
|
||||
"description": "Date of the snapshot (UTC timestamp)",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"additionalProperties": False,
|
||||
"required": ["snapshot_id", "name", "created_at", "project_id"]
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
#!/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/>.
|
||||
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
from gns3server.controller.project import Project
|
||||
from gns3server.controller.snapshot import Snapshot
|
||||
|
||||
from tests.utils import AsyncioMagicMock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(controller):
|
||||
project = Project(controller=controller, name="Test")
|
||||
controller._projects[project.id] = project
|
||||
return project
|
||||
|
||||
|
||||
def test_snapshot_name(project):
|
||||
"""
|
||||
Test create a snapshot object with a name
|
||||
"""
|
||||
snapshot = Snapshot(project, name="test1")
|
||||
assert snapshot.name == "test1"
|
||||
assert snapshot._created_at > 0
|
||||
assert snapshot.path.startswith(os.path.join(project.path, "snapshots", "test1_"))
|
||||
assert snapshot.path.endswith(".gns3project")
|
||||
|
||||
# Check if UTC conversion doesn't corrupt the path
|
||||
snap2 = Snapshot(project, filename=os.path.basename(snapshot.path))
|
||||
assert snap2.path == snapshot.path
|
||||
|
||||
|
||||
def test_snapshot_filename(project):
|
||||
"""
|
||||
Test create a snapshot object with a filename
|
||||
"""
|
||||
snapshot = Snapshot(project, filename="test1_260716_100439.gns3project")
|
||||
assert snapshot.name == "test1"
|
||||
assert snapshot._created_at == 1469527479.0
|
||||
assert snapshot.path == os.path.join(project.path, "snapshots", "test1_260716_100439.gns3project")
|
||||
|
||||
|
||||
def test_json(project):
|
||||
snapshot = Snapshot(project, filename="test1_260716_100439.gns3project")
|
||||
assert snapshot.__json__() == {
|
||||
"snapshot_id": snapshot._id,
|
||||
"name": "test1",
|
||||
"project_id": project.id,
|
||||
"created_at": 1469527479
|
||||
}
|
||||
|
||||
|
||||
def test_restore(project, controller, async_run):
|
||||
compute = AsyncioMagicMock()
|
||||
compute.id = "local"
|
||||
controller._computes["local"] = compute
|
||||
response = AsyncioMagicMock()
|
||||
response.json = {"console": 2048}
|
||||
compute.post = AsyncioMagicMock(return_value=response)
|
||||
|
||||
async_run(project.add_node(compute, "test1", None, node_type="vpcs", properties={"startup_config": "test.cfg"}))
|
||||
|
||||
snapshot = async_run(project.snapshot(name="test"))
|
||||
|
||||
# We add a node after the snapshots
|
||||
async_run(project.add_node(compute, "test2", None, node_type="vpcs", properties={"startup_config": "test.cfg"}))
|
||||
|
||||
# project-files should be reset when reimporting
|
||||
test_file = os.path.join(project.path, "project-files", "test.txt")
|
||||
os.makedirs(os.path.join(project.path, "project-files"))
|
||||
open(test_file, "a+").close()
|
||||
|
||||
assert os.path.exists(test_file)
|
||||
assert len(project.nodes) == 2
|
||||
|
||||
with patch("gns3server.config.Config.get_section_config", return_value={"local": True}):
|
||||
async_run(snapshot.restore())
|
||||
|
||||
project = controller.get_project(project.id)
|
||||
assert not os.path.exists(test_file)
|
||||
assert len(project.nodes) == 1
|
@ -0,0 +1,60 @@
|
||||
#!/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/>.
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(http_controller, controller):
|
||||
u = str(uuid.uuid4())
|
||||
query = {"name": "test", "project_id": u}
|
||||
response = http_controller.post("/projects", query)
|
||||
project = controller.get_project(u)
|
||||
|
||||
return project
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def snapshot(project, async_run):
|
||||
snapshot = async_run(project.snapshot("test"))
|
||||
return snapshot
|
||||
|
||||
|
||||
def test_list_snapshots(http_controller, project, snapshot):
|
||||
response = http_controller.get("/projects/{}/snapshots".format(project.id), example=True)
|
||||
assert response.status == 200
|
||||
assert len(response.json) == 1
|
||||
|
||||
|
||||
def test_delete_snapshot(http_controller, project, snapshot):
|
||||
response = http_controller.delete("/projects/{}/snapshots/{}".format(project.id, snapshot.id), example=True)
|
||||
assert response.status == 204
|
||||
assert not os.path.exists(snapshot.path)
|
||||
|
||||
|
||||
def test_restore_snapshot(http_controller, project, snapshot):
|
||||
response = http_controller.post("/projects/{}/snapshots/{}/restore".format(project.id, snapshot.id), example=True)
|
||||
assert response.status == 201
|
||||
assert response.json["name"] == project.name
|
||||
|
||||
|
||||
def test_create_snapshot(http_controller, project):
|
||||
response = http_controller.post("/projects/{}/snapshots".format(project.id), {"name": "snap1"}, example=True)
|
||||
assert response.status == 201
|
||||
assert len(os.listdir(os.path.join(project.path, "snapshots"))) == 1
|
Loading…
Reference in new issue