/
share_snapshots.py
292 lines (235 loc) · 10.5 KB
/
share_snapshots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# Copyright 2013 NetApp
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""The share snapshots api."""
import ast
from http import client as http_client
from oslo_log import log
import webob
from webob import exc
from manila.api import common
from manila.api.openstack import api_version_request as api_version
from manila.api.openstack import wsgi
from manila.api.views import share_snapshots as snapshot_views
from manila import db
from manila import exception
from manila.i18n import _
from manila import policy
from manila import share
from manila import utils
LOG = log.getLogger(__name__)
class ShareSnapshotMixin(object):
"""Mixin class for Share Snapshot Controllers."""
def _update(self, *args, **kwargs):
db.share_snapshot_update(*args, **kwargs)
def _get(self, *args, **kwargs):
return self.share_api.get_snapshot(*args, **kwargs)
def _delete(self, *args, **kwargs):
return self.share_api.delete_snapshot(*args, **kwargs)
def show(self, req, id):
"""Return data about the given snapshot."""
context = req.environ['manila.context']
try:
snapshot = self.share_api.get_snapshot(context, id)
# Snapshot with no instances is filtered out.
if snapshot.get('status') is None:
raise exc.HTTPNotFound()
except exception.NotFound:
raise exc.HTTPNotFound()
return self._view_builder.detail(req, snapshot)
def delete(self, req, id):
"""Delete a snapshot."""
context = req.environ['manila.context']
LOG.info("Delete snapshot with id: %s", id, context=context)
policy.check_policy(context, 'share', 'delete_snapshot')
try:
snapshot = self.share_api.get_snapshot(context, id)
self.share_api.delete_snapshot(context, snapshot)
except exception.NotFound:
raise exc.HTTPNotFound()
return webob.Response(status_int=http_client.ACCEPTED)
def index(self, req):
"""Returns a summary list of snapshots."""
req.GET.pop('name~', None)
req.GET.pop('description~', None)
req.GET.pop('description', None)
return self._get_snapshots(req, is_detail=False)
def detail(self, req):
"""Returns a detailed list of snapshots."""
req.GET.pop('name~', None)
req.GET.pop('description~', None)
req.GET.pop('description', None)
return self._get_snapshots(req, is_detail=True)
def _get_snapshots(self, req, is_detail):
"""Returns a list of snapshots."""
context = req.environ['manila.context']
search_opts = {}
search_opts.update(req.GET)
params = common.get_pagination_params(req)
limit, offset = [params.get('limit'), params.get('offset')]
# Remove keys that are not related to share attrs
search_opts.pop('limit', None)
search_opts.pop('offset', None)
show_count = False
if 'with_count' in search_opts:
show_count = utils.get_bool_from_api_params(
'with_count', search_opts)
search_opts.pop('with_count')
sort_key, sort_dir = common.get_sort_params(search_opts)
key_dict = {"name": "display_name",
"description": "display_description"}
for key in key_dict:
if sort_key == key:
sort_key = key_dict[key]
# NOTE(vponomaryov): Manila stores in DB key 'display_name', but
# allows to use both keys 'name' and 'display_name'. It is leftover
# from Cinder v1 and v2 APIs.
if 'name' in search_opts:
search_opts['display_name'] = search_opts.pop('name')
if 'description' in search_opts:
search_opts['display_description'] = search_opts.pop(
'description')
# Deserialize dicts
if req.api_version_request >= api_version.APIVersionRequest("2.73"):
if 'metadata' in search_opts:
try:
search_opts['metadata'] = ast.literal_eval(
search_opts['metadata'])
except ValueError:
msg = _('Invalid value for metadata filter.')
raise webob.exc.HTTPBadRequest(explanation=msg)
else:
search_opts.pop('metadata', None)
# like filter
for key, db_key in (('name~', 'display_name~'),
('description~', 'display_description~')):
if key in search_opts:
search_opts[db_key] = search_opts.pop(key)
common.remove_invalid_options(context, search_opts,
self._get_snapshots_search_options())
total_count = None
if show_count:
count, snapshots = self.share_api.get_all_snapshots_with_count(
context, search_opts=search_opts, limit=limit, offset=offset,
sort_key=sort_key, sort_dir=sort_dir)
total_count = count
else:
snapshots = self.share_api.get_all_snapshots(
context, search_opts=search_opts, limit=limit, offset=offset,
sort_key=sort_key, sort_dir=sort_dir)
if is_detail:
snapshots = self._view_builder.detail_list(
req, snapshots, total_count)
else:
snapshots = self._view_builder.summary_list(
req, snapshots, total_count)
return snapshots
def _get_snapshots_search_options(self):
"""Return share snapshot search options allowed by non-admin."""
return ('display_name', 'status', 'share_id', 'size', 'display_name~',
'display_description~', 'display_description', 'metadata')
def update(self, req, id, body):
"""Update a snapshot."""
context = req.environ['manila.context']
policy.check_policy(context, 'share', 'snapshot_update')
if not body or 'snapshot' not in body:
raise exc.HTTPUnprocessableEntity()
snapshot_data = body['snapshot']
valid_update_keys = (
'display_name',
'display_description',
)
update_dict = {key: snapshot_data[key]
for key in valid_update_keys
if key in snapshot_data}
common.check_display_field_length(
update_dict.get('display_name'), 'display_name')
common.check_display_field_length(
update_dict.get('display_description'), 'display_description')
try:
snapshot = self.share_api.get_snapshot(context, id)
except exception.NotFound:
raise exc.HTTPNotFound()
snapshot = self.share_api.snapshot_update(context, snapshot,
update_dict)
snapshot.update(update_dict)
return self._view_builder.detail(req, snapshot)
@wsgi.response(202)
def create(self, req, body):
"""Creates a new snapshot."""
context = req.environ['manila.context']
if not self.is_valid_body(body, 'snapshot'):
raise exc.HTTPUnprocessableEntity()
snapshot = body['snapshot']
share_id = snapshot['share_id']
share = self.share_api.get(context, share_id)
# Verify that share can be snapshotted
if not share['snapshot_support']:
msg = _("Snapshots cannot be created for share '%s' "
"since it does not have that capability.") % share_id
LOG.error(msg)
raise exc.HTTPUnprocessableEntity(explanation=msg)
# we do not allow soft delete share with snapshot, and also
# do not allow create snapshot for shares in recycle bin,
# since it will lead to auto delete share failed.
if share['is_soft_deleted']:
msg = _("Snapshots cannot be created for share '%s' "
"since it has been soft deleted.") % share_id
raise exc.HTTPForbidden(explanation=msg)
LOG.info("Create snapshot from share %s",
share_id, context=context)
# NOTE(rushiagr): v2 API allows name instead of display_name
if 'name' in snapshot:
snapshot['display_name'] = snapshot.get('name')
common.check_display_field_length(
snapshot['display_name'], 'name')
del snapshot['name']
# NOTE(rushiagr): v2 API allows description instead of
# display_description
if 'description' in snapshot:
snapshot['display_description'] = snapshot.get('description')
common.check_display_field_length(
snapshot['display_description'], 'description')
del snapshot['description']
kwargs = {}
if req.api_version_request >= api_version.APIVersionRequest("2.73"):
if snapshot.get('metadata'):
metadata = snapshot.get('metadata')
kwargs.update({
'metadata': metadata,
})
new_snapshot = self.share_api.create_snapshot(
context,
share,
snapshot.get('display_name'),
snapshot.get('display_description'),
**kwargs)
return self._view_builder.detail(
req, dict(new_snapshot.items()))
class ShareSnapshotsController(ShareSnapshotMixin, wsgi.Controller,
wsgi.AdminActionsMixin):
"""The Share Snapshots API controller for the OpenStack API."""
resource_name = 'share_snapshot'
_view_builder_class = snapshot_views.ViewBuilder
def __init__(self):
super(ShareSnapshotsController, self).__init__()
self.share_api = share.API()
@wsgi.action('os-reset_status')
def snapshot_reset_status_legacy(self, req, id, body):
return self._reset_status(req, id, body)
@wsgi.action('os-force_delete')
def snapshot_force_delete_legacy(self, req, id, body):
return self._force_delete(req, id, body)
def create_resource():
return wsgi.Resource(ShareSnapshotsController())