snapshots.py 6.15 KB
Newer Older
Vangelis Koukis's avatar
Vangelis Koukis committed
1
# Copyright (C) 2010-2014 GRNET S.A.
2
#
Vangelis Koukis's avatar
Vangelis Koukis committed
3
4
5
6
# 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.
7
#
Vangelis Koukis's avatar
Vangelis Koukis committed
8
9
10
11
# 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.
12
#
Vangelis Koukis's avatar
Vangelis Koukis committed
13
14
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

16
import logging
17
import simplejson as json
18
from synnefo.db import transaction
19
from snf_django.lib.api import faults
20
from synnefo.plankton.backend import PlanktonBackend, OBJECT_ERROR
21
22
from synnefo.logic import backend
from synnefo.volume import util
23
from synnefo.util import units
24

25
26
log = logging.getLogger(__name__)

27
28
29

@transaction.commit_on_success
def create(user_id, volume, name, description, metadata, force=False):
30
31
32
33
34
35
36
37
38
    """Create a snapshot from a given volume

    Create a snapshot from a given volume. The snapshot is first created as
    a file in Pithos, with specified metadata to indicate that it is a
    snapshot. Then a job is sent to Ganeti backend to create the actual
    snapshot of the volume.

    Snapshots are only supported for volumes of ext_ disk template. Also,
    the volume must be attached to some server.
39

40
41
    """

42
43
44
    if name is None:
        raise faults.BadRequest("Snapshot 'name' is required")

45
    # Check that taking a snapshot is feasible
46
    if volume.machine is None:
47
        raise faults.BadRequest("Cannot snapshot a detached volume!")
48
49
50
    if volume.status not in ["AVAILABLE", "IN_USE"]:
        raise faults.BadRequest("Cannot create snapshot while volume is in"
                                " '%s' status" % volume.status)
51

52
53
54
55
56
    volume_type = volume.volume_type
    if not volume_type.disk_template.startswith("ext_"):
        msg = ("Cannot take a snapshot from a volume with volume type '%s' and"
               " '%s' disk template" %
               (volume_type.id, volume_type.disk_template))
57
58
        raise faults.BadRequest(msg)

59
60
    # Increase the snapshot counter of the volume that is used in order to
    # generate unique snapshot names
61
62
    volume.snapshot_counter += 1
    volume.save()
63
    transaction.commit()
64

65
    snapshot_metadata = {
66
67
68
        "name": name,
        "disk_format": "diskdump",
        "container_format": "bare",
69
        # Snapshot specific
70
71
        "description": description,
        "volume_id": volume.id,
72
73
74
75
76
77
    }

    # Snapshots are used as images. We set the most important properties
    # that are being used for images. We set 'EXCLUDE_ALL_TASKS' to bypass
    # image customization. Also, we get some basic metadata for the volume from
    # the server that the volume is attached
78
79
    metadata.update({"EXCLUDE_ALL_TASKS": "yes",
                     "description": description})
80
81
82
83
84
85
86
87
    if volume.index == 0:
        # Copy the metadata of the VM into the image properties only when the
        # volume is the root volume of the VM.
        vm_metadata = dict(volume.machine.metadata
                                         .filter(meta_key__in=["OS", "users"])
                                         .values_list("meta_key",
                                                      "meta_value"))
        metadata.update(vm_metadata)
88

89
90
    snapshot_properties = PlanktonBackend._prefix_properties(metadata)
    snapshot_metadata.update(snapshot_properties)
91

92
93
    # Generate a name for the Archipelago mapfile.
    mapfile = generate_mapfile_name(volume)
94

95
    # Convert size from Gbytes to bytes
96
    size = volume.size << 30
97

98
    with PlanktonBackend(user_id) as b:
99
100
101
102
103
104
105
106
107
108
        try:
            snapshot_id = b.register_snapshot(name=name,
                                              mapfile=mapfile,
                                              size=size,
                                              metadata=snapshot_metadata)
        except faults.OverLimit:
            msg = ("Resource limit exceeded for your account."
                   " Not enough storage space to create snapshot of"
                   " %s size." % units.show(size, "bytes", "gb"))
            raise faults.OverLimit(msg)
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        try:
            job_id = backend.snapshot_instance(volume.machine, volume,
                                               snapshot_name=mapfile,
                                               snapshot_id=snapshot_id)
        except:
            # If failed to enqueue job to Ganeti, mark snapshot as ERROR
            b.update_snapshot_state(snapshot_id, OBJECT_ERROR)

        # Store the backend and job id as metadata in the snapshot in order
        # to make reconciliation based on the Ganeti job possible.
        backend_info = {
            "ganeti_job_id": job_id,
            "ganeti_backend_id": volume.machine.backend_id
        }
        metadata = {"backend_info": json.dumps(backend_info)}
        b.update_metadata(snapshot_id, metadata)
126

127
    snapshot = util.get_snapshot(user_id, snapshot_id)
128
129
130
131

    return snapshot


132
133
def generate_mapfile_name(volume):
    """Helper function to generate a name for the Archipelago mapfile."""
134
    # time = isoformat(datetime.datetime.now())
135
136
    return "snf-snap-%s-%s" % (volume.id,
                               volume.snapshot_counter)
137
138
139
140


@transaction.commit_on_success
def delete(snapshot):
141
142
143
144
145
    """Delete a snapshot.

    Delete a snapshot by deleting the corresponding file from Pithos.

    """
146
    user_id = snapshot["owner"]
147
    log.info("Deleting snapshot '%s'", snapshot["location"])
148
    with PlanktonBackend(user_id) as pithos_backend:
Christos Stavrakakis's avatar
Christos Stavrakakis committed
149
        pithos_backend.delete_snapshot(snapshot["id"])
150
    return snapshot
151
152


153
154
def update(snapshot, name=None, description=None):
    """Update a snapshot
155

156
157
158
159
160
161
162
163
164
165
    Update the name or description of a snapshot.
    """
    metadata = {}
    if name is not None:
        metadata["name"] = name
    if description is not None:
        metadata["description"] = description
    if not metadata:
        return
    user_id = snapshot["owner"]
166
    with PlanktonBackend(user_id) as b:
167
        return b.update_metadata(snapshot["id"], metadata)