/
images.py
1516 lines (1343 loc) · 62.7 KB
/
images.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2012 OpenStack Foundation.
# 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.
import hashlib
import os
import re
from castellan.common import exception as castellan_exception
from castellan import key_manager
import glance_store
from glance_store import location
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils as json
from oslo_utils import encodeutils
import six
from six.moves import http_client as http
import six.moves.urllib.parse as urlparse
import webob.exc
from glance.api import common
from glance.api import policy
from glance.common import exception
from glance.common import location_strategy
from glance.common import store_utils
from glance.common import timeutils
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
from glance.i18n import _, _LI, _LW
import glance.notifier
import glance.schema
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
CONF.import_opt('disk_formats', 'glance.common.config', group='image_format')
CONF.import_opt('container_formats', 'glance.common.config',
group='image_format')
CONF.import_opt('show_multiple_locations', 'glance.common.config')
CONF.import_opt('hashing_algorithm', 'glance.common.config')
class ImagesController(object):
def __init__(self, db_api=None, policy_enforcer=None, notifier=None,
store_api=None):
self.db_api = db_api or glance.db.get_api()
self.policy = policy_enforcer or policy.Enforcer()
self.notifier = notifier or glance.notifier.Notifier()
self.store_api = store_api or glance_store
self.gateway = glance.gateway.Gateway(self.db_api, self.store_api,
self.notifier, self.policy)
self._key_manager = key_manager.API(CONF)
@utils.mutating
def create(self, req, image, extra_properties, tags):
image_factory = self.gateway.get_image_factory(req.context)
image_repo = self.gateway.get_repo(req.context)
try:
image = image_factory.new_image(extra_properties=extra_properties,
tags=tags, **image)
image_repo.add(image)
except (exception.DuplicateLocation,
exception.Invalid) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except (exception.ReservedProperty,
exception.ReadonlyProperty) as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to create image")
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.LimitExceeded as e:
LOG.warn(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
except TypeError as e:
LOG.debug(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPBadRequest(explanation=e)
return image
@utils.mutating
def import_image(self, req, image_id, body):
image_repo = self.gateway.get_repo(req.context)
task_factory = self.gateway.get_task_factory(req.context)
executor_factory = self.gateway.get_task_executor_factory(req.context)
task_repo = self.gateway.get_task_repo(req.context)
import_method = body.get('method').get('name')
uri = body.get('method').get('uri')
all_stores_must_succeed = body.get('all_stores_must_succeed', True)
try:
image = image_repo.get(image_id)
if image.status == 'active' and import_method != "copy-image":
msg = _("Image with status active cannot be target for import")
raise exception.Conflict(msg)
if image.status != 'active' and import_method == "copy-image":
msg = _("Only images with status active can be targeted for "
"copying")
raise exception.Conflict(msg)
if image.status != 'queued' and import_method == 'web-download':
msg = _("Image needs to be in 'queued' state to use "
"'web-download' method")
raise exception.Conflict(msg)
if (image.status != 'uploading' and
import_method == 'glance-direct'):
msg = _("Image needs to be staged before 'glance-direct' "
"method can be used")
raise exception.Conflict(msg)
if not getattr(image, 'container_format', None):
msg = _("'container_format' needs to be set before import")
raise exception.Conflict(msg)
if not getattr(image, 'disk_format', None):
msg = _("'disk_format' needs to be set before import")
raise exception.Conflict(msg)
stores = [None]
if CONF.enabled_backends:
try:
stores = utils.get_stores_from_request(req, body)
except glance_store.UnknownScheme as exc:
LOG.warn(exc.msg)
raise exception.Conflict(exc.msg)
# NOTE(abhishekk): If all_stores is specified and import_method is
# copy_image, then remove those stores where image is already
# present.
all_stores = body.get('all_stores', False)
if import_method == 'copy-image' and all_stores:
for loc in image.locations:
existing_store = loc['metadata']['store']
if existing_store in stores:
LOG.debug("Removing store '%s' from all stores as "
"image is already available in that "
"store." % existing_store)
stores.remove(existing_store)
if len(stores) == 0:
LOG.info(_LI("Exiting copying workflow as image is "
"available in all configured stores."))
return image_id
# validate if image is already existing in given stores when
# all_stores is False
if import_method == 'copy-image' and not all_stores:
for loc in image.locations:
existing_store = loc['metadata']['store']
if existing_store in stores:
msg = _("Image is already present at store "
"'%s'") % existing_store
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.Conflict as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
if (not all_stores_must_succeed) and (not CONF.enabled_backends):
msg = (_("All_stores_must_succeed can only be set with "
"enabled_backends %s") % uri)
raise webob.exc.HTTPBadRequest(explanation=msg)
task_input = {'image_id': image_id,
'import_req': body,
'backend': stores}
if (import_method == 'web-download' and
not utils.validate_import_uri(uri)):
LOG.debug("URI for web-download does not pass filtering: %s", uri)
msg = (_("URI for web-download does not pass filtering: %s") % uri)
raise webob.exc.HTTPBadRequest(explanation=msg)
try:
import_task = task_factory.new_task(task_type='api_image_import',
owner=req.context.owner,
task_input=task_input)
task_repo.add(import_task)
task_executor = executor_factory.new_task_executor(req.context)
pool = common.get_thread_pool("tasks_eventlet_pool")
pool.spawn_n(import_task.run, task_executor)
except exception.Forbidden as e:
LOG.debug("User not permitted to create image import task.")
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.Conflict as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except exception.InvalidImageStatusTransition as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except ValueError as e:
LOG.debug("Cannot import data for image %(id)s: %(e)s",
{'id': image_id,
'e': encodeutils.exception_to_unicode(e)})
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
return image_id
def index(self, req, marker=None, limit=None, sort_key=None,
sort_dir=None, filters=None, member_status='accepted'):
sort_key = ['created_at'] if not sort_key else sort_key
sort_dir = ['desc'] if not sort_dir else sort_dir
result = {}
if filters is None:
filters = {}
filters['deleted'] = False
os_hidden = filters.get('os_hidden', 'false').lower()
if os_hidden not in ['true', 'false']:
message = _("Invalid value '%s' for 'os_hidden' filter."
" Valid values are 'true' or 'false'.") % os_hidden
raise webob.exc.HTTPBadRequest(explanation=message)
# ensure the type of os_hidden is boolean
filters['os_hidden'] = os_hidden == 'true'
protected = filters.get('protected')
if protected is not None:
if protected not in ['true', 'false']:
message = _("Invalid value '%s' for 'protected' filter."
" Valid values are 'true' or 'false'.") % protected
raise webob.exc.HTTPBadRequest(explanation=message)
# ensure the type of protected is boolean
filters['protected'] = protected == 'true'
if limit is None:
limit = CONF.limit_param_default
limit = min(CONF.api_limit_max, limit)
image_repo = self.gateway.get_repo(req.context)
try:
images = image_repo.list(marker=marker, limit=limit,
sort_key=sort_key,
sort_dir=sort_dir,
filters=filters,
member_status=member_status)
if len(images) != 0 and len(images) == limit:
result['next_marker'] = images[-1].image_id
except (exception.NotFound, exception.InvalidSortKey,
exception.InvalidFilterRangeValue,
exception.InvalidParameterValue,
exception.InvalidFilterOperatorValue) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to retrieve images index")
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
result['images'] = images
return result
def show(self, req, image_id):
image_repo = self.gateway.get_repo(req.context)
try:
return image_repo.get(image_id)
except exception.Forbidden as e:
LOG.debug("User not permitted to show image '%s'", image_id)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
@utils.mutating
def update(self, req, image_id, changes):
image_repo = self.gateway.get_repo(req.context)
try:
image = image_repo.get(image_id)
for change in changes:
change_method_name = '_do_%s' % change['op']
change_method = getattr(self, change_method_name)
change_method(req, image, change)
if changes:
image_repo.save(image)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except (exception.Invalid, exception.BadStoreUri) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.Forbidden as e:
LOG.debug("User not permitted to update image '%s'", image_id)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.StorageQuotaFull as e:
msg = (_("Denying attempt to upload image because it exceeds the"
" quota: %s") % encodeutils.exception_to_unicode(e))
LOG.warn(msg)
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=msg, request=req, content_type='text/plain')
except exception.LimitExceeded as e:
LOG.exception(encodeutils.exception_to_unicode(e))
raise webob.exc.HTTPRequestEntityTooLarge(
explanation=e.msg, request=req, content_type='text/plain')
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
return image
def _do_replace(self, req, image, change):
path = change['path']
path_root = path[0]
value = change['value']
if path_root == 'locations' and not value:
msg = _("Cannot set locations to empty list.")
raise webob.exc.HTTPForbidden(msg)
elif path_root == 'locations' and value:
self._do_replace_locations(image, value)
elif path_root == 'owner' and req.context.is_admin == False:
msg = _("Owner can't be updated by non admin.")
raise webob.exc.HTTPForbidden(msg)
else:
if hasattr(image, path_root):
setattr(image, path_root, value)
elif path_root in image.extra_properties:
image.extra_properties[path_root] = value
else:
msg = _("Property %s does not exist.")
raise webob.exc.HTTPConflict(msg % path_root)
def _do_add(self, req, image, change):
path = change['path']
path_root = path[0]
value = change['value']
json_schema_version = change.get('json_schema_version', 10)
if path_root == 'locations':
self._do_add_locations(image, path[1], value)
else:
if ((hasattr(image, path_root) or
path_root in image.extra_properties)
and json_schema_version == 4):
msg = _("Property %s already present.")
raise webob.exc.HTTPConflict(msg % path_root)
if hasattr(image, path_root):
setattr(image, path_root, value)
else:
image.extra_properties[path_root] = value
def _do_remove(self, req, image, change):
path = change['path']
path_root = path[0]
if path_root == 'locations':
try:
self._do_remove_locations(image, path[1])
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(e.msg)
else:
if hasattr(image, path_root):
msg = _("Property %s may not be removed.")
raise webob.exc.HTTPForbidden(msg % path_root)
elif path_root in image.extra_properties:
del image.extra_properties[path_root]
else:
msg = _("Property %s does not exist.")
raise webob.exc.HTTPConflict(msg % path_root)
def _delete_encryption_key(self, context, image):
props = image.extra_properties
cinder_encryption_key_id = props.get('cinder_encryption_key_id')
if cinder_encryption_key_id is None:
return
deletion_policy = props.get('cinder_encryption_key_deletion_policy',
'')
if deletion_policy != 'on_image_deletion':
return
try:
self._key_manager.delete(context, cinder_encryption_key_id)
except castellan_exception.Forbidden:
msg = ('Not allowed to delete encryption key %s' %
cinder_encryption_key_id)
LOG.warn(msg)
except (castellan_exception.ManagedObjectNotFoundError, KeyError):
msg = 'Could not find encryption key %s' % cinder_encryption_key_id
LOG.warn(msg)
except castellan_exception.KeyManagerError:
msg = ('Failed to delete cinder encryption key %s' %
cinder_encryption_key_id)
LOG.warn(msg)
@utils.mutating
def delete_from_store(self, req, store_id, image_id):
if not CONF.enabled_backends:
raise webob.exc.HTTPNotFound()
if store_id not in CONF.enabled_backends:
msg = (_("The selected store %s is not available on this node.") %
store_id)
raise webob.exc.HTTPConflict(explanation=msg)
image_repo = self.gateway.get_repo(req.context)
try:
image = image_repo.get(image_id)
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
except exception.NotFound:
msg = (_("Failed to find image %(image_id)s") %
{'image_id': image_id})
raise webob.exc.HTTPNotFound(explanation=msg)
if image.status != 'active':
msg = _("It's not allowed to remove image data from store if "
"image status is not 'active'")
raise webob.exc.HTTPConflict(explanation=msg)
if len(image.locations) == 1:
LOG.debug("User forbidden to remove last location of image %s",
image_id)
msg = _("Cannot delete image data from the only store containing "
"it. Consider deleting the image instead.")
raise webob.exc.HTTPForbidden(explanation=msg)
try:
# NOTE(jokke): Here we go through the locations list and act on
# the first hit. image.locations.pop() will actually remove the
# data from the backend as well as remove the location object
# from the list.
for pos, loc in enumerate(image.locations):
if loc['metadata'].get('store') == store_id:
image.locations.pop(pos)
break
else:
msg = (_("Image %(iid)s is not stored in store %(sid)s.") %
{'iid': image_id, 'sid': store_id})
raise exception.Invalid(msg)
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.Invalid as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except glance_store.exceptions.HasSnapshot as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except glance_store.exceptions.InUseByStore as e:
msg = ("The data for Image %(id)s could not be deleted "
"because it is in use: %(exc)s" % {"id": image_id,
"exc": e.msg})
LOG.warning(msg)
raise webob.exc.HTTPConflict(explanation=msg)
except Exception as e:
raise webob.exc.HTTPInternalServerError(
explanation=encodeutils.exception_to_unicode(e))
image_repo.save(image)
@utils.mutating
def delete(self, req, image_id):
image_repo = self.gateway.get_repo(req.context)
try:
image = image_repo.get(image_id)
# NOTE(abhishekk): Delete the data from staging area
if CONF.enabled_backends:
separator, staging_dir = store_utils.get_dir_separator()
file_path = "%s%s%s" % (staging_dir,
separator,
image_id)
try:
fn_call = glance_store.get_store_from_store_identifier
staging_store = fn_call('os_glance_staging_store')
loc = location.get_location_from_uri_and_backend(
file_path, 'os_glance_staging_store')
staging_store.delete(loc)
except (glance_store.exceptions.NotFound,
glance_store.exceptions.UnknownScheme):
pass
else:
file_path = str(
CONF.node_staging_uri + '/' + image_id)[7:]
if os.path.exists(file_path):
try:
LOG.debug(
"After upload to the backend, deleting staged "
"image data from %(fn)s", {'fn': file_path})
os.unlink(file_path)
except OSError as e:
LOG.error(
"After upload to backend, deletion of staged "
"image data from %(fn)s has failed because "
"[Errno %(en)d]", {'fn': file_path,
'en': e.errno})
else:
LOG.warning(_(
"After upload to backend, deletion of staged "
"image data has failed because "
"it cannot be found at %(fn)s"), {'fn': file_path})
image.delete()
self._delete_encryption_key(req.context, image)
image_repo.remove(image)
except (glance_store.Forbidden, exception.Forbidden) as e:
LOG.debug("User not permitted to delete image '%s'", image_id)
raise webob.exc.HTTPForbidden(explanation=e.msg)
except (glance_store.NotFound, exception.NotFound):
msg = (_("Failed to find image %(image_id)s to delete") %
{'image_id': image_id})
LOG.warn(msg)
raise webob.exc.HTTPNotFound(explanation=msg)
except glance_store.exceptions.InUseByStore as e:
msg = (_("Image %(id)s could not be deleted "
"because it is in use: %(exc)s") %
{"id": image_id,
"exc": e.msg})
LOG.warn(msg)
raise webob.exc.HTTPConflict(explanation=msg)
except glance_store.exceptions.HasSnapshot as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except exception.InvalidImageStatusTransition as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except exception.NotAuthenticated as e:
raise webob.exc.HTTPUnauthorized(explanation=e.msg)
def _validate_validation_data(self, image, locations):
val_data = {}
for loc in locations:
if 'validation_data' not in loc:
continue
for k, v in loc['validation_data'].items():
if val_data.get(k, v) != v:
msg = _("Conflicting values for %s") % k
raise webob.exc.HTTPConflict(explanation=msg)
val_data[k] = v
# NOTE(imacdonn): values may be provided for items which are
# already set, so long as the values exactly match. In this
# case, nothing actually needs to be updated, but we should
# reject the request if there's an apparent attempt to supply
# a different value.
new_val_data = {}
for k, v in val_data.items():
current = getattr(image, k)
if v == current:
continue
if current:
msg = _("%s is already set with a different value") % k
raise webob.exc.HTTPConflict(explanation=msg)
new_val_data[k] = v
if not new_val_data:
return {}
if image.status != 'queued':
msg = _("New value(s) for %s may only be provided when image "
"status is 'queued'") % ', '.join(new_val_data.keys())
raise webob.exc.HTTPConflict(explanation=msg)
if 'checksum' in new_val_data:
try:
checksum_bytes = bytearray.fromhex(new_val_data['checksum'])
except ValueError:
msg = (_("checksum (%s) is not a valid hexadecimal value") %
new_val_data['checksum'])
raise webob.exc.HTTPConflict(explanation=msg)
if len(checksum_bytes) != 16:
msg = (_("checksum (%s) is not the correct size for md5 "
"(should be 16 bytes)") %
new_val_data['checksum'])
raise webob.exc.HTTPConflict(explanation=msg)
hash_algo = new_val_data.get('os_hash_algo')
if hash_algo != CONF['hashing_algorithm']:
msg = (_("os_hash_algo must be %(want)s, not %(got)s") %
{'want': CONF['hashing_algorithm'], 'got': hash_algo})
raise webob.exc.HTTPConflict(explanation=msg)
try:
hash_bytes = bytearray.fromhex(new_val_data['os_hash_value'])
except ValueError:
msg = (_("os_hash_value (%s) is not a valid hexadecimal value") %
new_val_data['os_hash_value'])
raise webob.exc.HTTPConflict(explanation=msg)
want_size = hashlib.new(hash_algo).digest_size
if len(hash_bytes) != want_size:
msg = (_("os_hash_value (%(value)s) is not the correct size for "
"%(algo)s (should be %(want)d bytes)") %
{'value': new_val_data['os_hash_value'],
'algo': hash_algo,
'want': want_size})
raise webob.exc.HTTPConflict(explanation=msg)
return new_val_data
def _get_locations_op_pos(self, path_pos, max_pos, allow_max):
if path_pos is None or max_pos is None:
return None
pos = max_pos if allow_max else max_pos - 1
if path_pos.isdigit():
pos = int(path_pos)
elif path_pos != '-':
return None
if not (allow_max or 0 <= pos < max_pos):
return None
return pos
def _do_replace_locations(self, image, value):
if CONF.show_multiple_locations == False:
msg = _("It's not allowed to update locations if locations are "
"invisible.")
raise webob.exc.HTTPForbidden(explanation=msg)
if image.status not in ('active', 'queued'):
msg = _("It's not allowed to replace locations if image status is "
"%s.") % image.status
raise webob.exc.HTTPConflict(explanation=msg)
val_data = self._validate_validation_data(image, value)
# NOTE(abhishekk): get glance store based on location uri
if CONF.enabled_backends:
store_utils.update_store_in_locations(value, image.image_id)
try:
# NOTE(flwang): _locations_proxy's setattr method will check if
# the update is acceptable.
image.locations = value
if image.status == 'queued':
for k, v in val_data.items():
setattr(image, k, v)
image.status = 'active'
except (exception.BadStoreUri, exception.DuplicateLocation) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except ValueError as ve: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(ve))
def _do_add_locations(self, image, path_pos, value):
if CONF.show_multiple_locations == False:
msg = _("It's not allowed to add locations if locations are "
"invisible.")
raise webob.exc.HTTPForbidden(explanation=msg)
if image.status not in ('active', 'queued'):
msg = _("It's not allowed to add locations if image status is "
"%s.") % image.status
raise webob.exc.HTTPConflict(explanation=msg)
val_data = self._validate_validation_data(image, [value])
# NOTE(abhishekk): get glance store based on location uri
if CONF.enabled_backends:
store_utils.update_store_in_locations([value], image.image_id)
pos = self._get_locations_op_pos(path_pos,
len(image.locations), True)
if pos is None:
msg = _("Invalid position for adding a location.")
raise webob.exc.HTTPBadRequest(explanation=msg)
try:
image.locations.insert(pos, value)
if image.status == 'queued':
for k, v in val_data.items():
setattr(image, k, v)
image.status = 'active'
except (exception.BadStoreUri, exception.DuplicateLocation) as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
except ValueError as e: # update image status failed.
raise webob.exc.HTTPBadRequest(
explanation=encodeutils.exception_to_unicode(e))
def _do_remove_locations(self, image, path_pos):
if CONF.show_multiple_locations == False:
msg = _("It's not allowed to remove locations if locations are "
"invisible.")
raise webob.exc.HTTPForbidden(explanation=msg)
if image.status not in ('active'):
msg = _("It's not allowed to remove locations if image status is "
"%s.") % image.status
raise webob.exc.HTTPConflict(explanation=msg)
if len(image.locations) == 1:
LOG.debug("User forbidden to remove last location of image %s",
image.image_id)
msg = _("Cannot remove last location in the image.")
raise exception.Forbidden(msg)
pos = self._get_locations_op_pos(path_pos,
len(image.locations), False)
if pos is None:
msg = _("Invalid position for removing a location.")
raise webob.exc.HTTPBadRequest(explanation=msg)
try:
# NOTE(zhiyan): this actually deletes the location
# from the backend store.
image.locations.pop(pos)
# TODO(jokke): Fix this, we should catch what store throws and
# provide definitely something else than IternalServerError to user.
except Exception as e:
raise webob.exc.HTTPInternalServerError(
explanation=encodeutils.exception_to_unicode(e))
class RequestDeserializer(wsgi.JSONRequestDeserializer):
_disallowed_properties = ('direct_url', 'self', 'file', 'schema')
_readonly_properties = ('created_at', 'updated_at', 'status', 'checksum',
'size', 'virtual_size', 'direct_url', 'self',
'file', 'schema', 'id', 'os_hash_algo',
'os_hash_value')
_reserved_properties = ('location', 'deleted', 'deleted_at')
_base_properties = ('checksum', 'created_at', 'container_format',
'disk_format', 'id', 'min_disk', 'min_ram', 'name',
'size', 'virtual_size', 'status', 'tags', 'owner',
'updated_at', 'visibility', 'protected', 'os_hidden')
_available_sort_keys = ('name', 'status', 'container_format',
'disk_format', 'size', 'id', 'created_at',
'updated_at')
_default_sort_key = 'created_at'
_default_sort_dir = 'desc'
_path_depth_limits = {'locations': {'add': 2, 'remove': 2, 'replace': 1}}
_supported_operations = ('add', 'remove', 'replace')
def __init__(self, schema=None):
super(RequestDeserializer, self).__init__()
self.schema = schema or get_schema()
def _get_request_body(self, request):
output = super(RequestDeserializer, self).default(request)
if 'body' not in output:
msg = _('Body expected in request.')
raise webob.exc.HTTPBadRequest(explanation=msg)
return output['body']
@classmethod
def _check_allowed(cls, image):
for key in cls._disallowed_properties:
if key in image:
msg = _("Attribute '%s' is read-only.") % key
raise webob.exc.HTTPForbidden(
explanation=six.text_type(msg))
def create(self, request):
body = self._get_request_body(request)
self._check_allowed(body)
try:
self.schema.validate(body)
except exception.InvalidObject as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
image = {}
properties = body
tags = properties.pop('tags', [])
for key in self._base_properties:
try:
# NOTE(flwang): Instead of changing the _check_unexpected
# of ImageFactory. It would be better to do the mapping
# at here.
if key == 'id':
image['image_id'] = properties.pop(key)
else:
image[key] = properties.pop(key)
except KeyError:
pass
# NOTE(abhishekk): Check if custom property key name is less than 255
# characters. Reference LP #1737952
for key in properties:
if len(key) > 255:
msg = (_("Custom property should not be greater than 255 "
"characters."))
raise webob.exc.HTTPBadRequest(explanation=msg)
return dict(image=image, extra_properties=properties, tags=tags)
def _get_change_operation_d10(self, raw_change):
op = raw_change.get('op')
if op is None:
msg = (_('Unable to find `op` in JSON Schema change. '
'It must be one of the following: %(available)s.') %
{'available': ', '.join(self._supported_operations)})
raise webob.exc.HTTPBadRequest(explanation=msg)
if op not in self._supported_operations:
msg = (_('Invalid operation: `%(op)s`. '
'It must be one of the following: %(available)s.') %
{'op': op,
'available': ', '.join(self._supported_operations)})
raise webob.exc.HTTPBadRequest(explanation=msg)
return op
def _get_change_operation_d4(self, raw_change):
op = None
for key in self._supported_operations:
if key in raw_change:
if op is not None:
msg = _('Operation objects must contain only one member'
' named "add", "remove", or "replace".')
raise webob.exc.HTTPBadRequest(explanation=msg)
op = key
if op is None:
msg = _('Operation objects must contain exactly one member'
' named "add", "remove", or "replace".')
raise webob.exc.HTTPBadRequest(explanation=msg)
return op
def _get_change_path_d10(self, raw_change):
try:
return raw_change['path']
except KeyError:
msg = _("Unable to find '%s' in JSON Schema change") % 'path'
raise webob.exc.HTTPBadRequest(explanation=msg)
def _get_change_path_d4(self, raw_change, op):
return raw_change[op]
def _decode_json_pointer(self, pointer):
"""Parse a json pointer.
Json Pointers are defined in
http://tools.ietf.org/html/draft-pbryan-zyp-json-pointer .
The pointers use '/' for separation between object attributes, such
that '/A/B' would evaluate to C in {"A": {"B": "C"}}. A '/' character
in an attribute name is encoded as "~1" and a '~' character is encoded
as "~0".
"""
self._validate_json_pointer(pointer)
ret = []
for part in pointer.lstrip('/').split('/'):
ret.append(part.replace('~1', '/').replace('~0', '~').strip())
return ret
def _validate_json_pointer(self, pointer):
"""Validate a json pointer.
We only accept a limited form of json pointers.
"""
if not pointer.startswith('/'):
msg = _('Pointer `%s` does not start with "/".') % pointer
raise webob.exc.HTTPBadRequest(explanation=msg)
if re.search(r'/\s*?/', pointer[1:]):
msg = _('Pointer `%s` contains adjacent "/".') % pointer
raise webob.exc.HTTPBadRequest(explanation=msg)
if len(pointer) > 1 and pointer.endswith('/'):
msg = _('Pointer `%s` end with "/".') % pointer
raise webob.exc.HTTPBadRequest(explanation=msg)
if pointer[1:].strip() == '/':
msg = _('Pointer `%s` does not contains valid token.') % pointer
raise webob.exc.HTTPBadRequest(explanation=msg)
if re.search('~[^01]', pointer) or pointer.endswith('~'):
msg = _('Pointer `%s` contains "~" not part of'
' a recognized escape sequence.') % pointer
raise webob.exc.HTTPBadRequest(explanation=msg)
def _get_change_value(self, raw_change, op):
if 'value' not in raw_change:
msg = _('Operation "%s" requires a member named "value".')
raise webob.exc.HTTPBadRequest(explanation=msg % op)
return raw_change['value']
def _validate_change(self, change):
path_root = change['path'][0]
if path_root in self._readonly_properties:
msg = _("Attribute '%s' is read-only.") % path_root
raise webob.exc.HTTPForbidden(explanation=six.text_type(msg))
if path_root in self._reserved_properties:
msg = _("Attribute '%s' is reserved.") % path_root
raise webob.exc.HTTPForbidden(explanation=six.text_type(msg))
if change['op'] == 'remove':
return
partial_image = None
if len(change['path']) == 1:
partial_image = {path_root: change['value']}
elif ((path_root in get_base_properties().keys()) and
(get_base_properties()[path_root].get('type', '') == 'array')):
# NOTE(zhiyan): client can use the PATCH API to add an element
# directly to an existing property
# Such as: 1. using '/locations/N' path to add a location
# to the image's 'locations' list at position N.
# (implemented)
# 2. using '/tags/-' path to append a tag to the
# image's 'tags' list at the end. (Not implemented)
partial_image = {path_root: [change['value']]}
if partial_image:
try:
self.schema.validate(partial_image)
except exception.InvalidObject as e:
raise webob.exc.HTTPBadRequest(explanation=e.msg)
def _validate_path(self, op, path):
path_root = path[0]
limits = self._path_depth_limits.get(path_root, {})
if len(path) != limits.get(op, 1):
msg = _("Invalid JSON pointer for this resource: "
"'/%s'") % '/'.join(path)
raise webob.exc.HTTPBadRequest(explanation=six.text_type(msg))
def _parse_json_schema_change(self, raw_change, draft_version):
if draft_version == 10:
op = self._get_change_operation_d10(raw_change)
path = self._get_change_path_d10(raw_change)
elif draft_version == 4:
op = self._get_change_operation_d4(raw_change)
path = self._get_change_path_d4(raw_change, op)
else:
msg = _('Unrecognized JSON Schema draft version')
raise webob.exc.HTTPBadRequest(explanation=msg)
path_list = self._decode_json_pointer(path)
return op, path_list
def update(self, request):
changes = []
content_types = {
'application/openstack-images-v2.0-json-patch': 4,
'application/openstack-images-v2.1-json-patch': 10,
}
if request.content_type not in content_types:
headers = {'Accept-Patch':
', '.join(sorted(content_types.keys()))}
raise webob.exc.HTTPUnsupportedMediaType(headers=headers)
json_schema_version = content_types[request.content_type]
body = self._get_request_body(request)
if not isinstance(body, list):
msg = _('Request body must be a JSON array of operation objects.')
raise webob.exc.HTTPBadRequest(explanation=msg)
for raw_change in body:
if not isinstance(raw_change, dict):
msg = _('Operations must be JSON objects.')
raise webob.exc.HTTPBadRequest(explanation=msg)
(op, path) = self._parse_json_schema_change(raw_change,
json_schema_version)
# NOTE(zhiyan): the 'path' is a list.
self._validate_path(op, path)
change = {'op': op, 'path': path,
'json_schema_version': json_schema_version}
if not op == 'remove':
change['value'] = self._get_change_value(raw_change, op)
self._validate_change(change)
changes.append(change)
return {'changes': changes}
def _validate_limit(self, limit):
try:
limit = int(limit)
except ValueError:
msg = _("limit param must be an integer")
raise webob.exc.HTTPBadRequest(explanation=msg)
if limit < 0:
msg = _("limit param must be positive")
raise webob.exc.HTTPBadRequest(explanation=msg)
return limit
def _validate_sort_key(self, sort_key):
if sort_key not in self._available_sort_keys:
msg = _('Invalid sort key: %(sort_key)s. '
'It must be one of the following: %(available)s.') % (
{'sort_key': sort_key,
'available': ', '.join(self._available_sort_keys)})
raise webob.exc.HTTPBadRequest(explanation=msg)
return sort_key
def _validate_sort_dir(self, sort_dir):
if sort_dir not in ['asc', 'desc']:
msg = _('Invalid sort direction: %s') % sort_dir
raise webob.exc.HTTPBadRequest(explanation=msg)
return sort_dir
def _validate_member_status(self, member_status):
if member_status not in ['pending', 'accepted', 'rejected', 'all']:
msg = _('Invalid status: %s') % member_status
raise webob.exc.HTTPBadRequest(explanation=msg)
return member_status
def _get_filters(self, filters):
visibility = filters.get('visibility')
if visibility:
if visibility not in ['community', 'public', 'private', 'shared',
'all']:
msg = _('Invalid visibility value: %s') % visibility
raise webob.exc.HTTPBadRequest(explanation=msg)