-
Notifications
You must be signed in to change notification settings - Fork 906
/
create_volume.py
1777 lines (1533 loc) · 77.4 KB
/
create_volume.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
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
# Copyright (c) 2013 OpenStack, LLC.
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 traceback
from oslo.config import cfg
from cinder import exception
from cinder.image import glance
from cinder import policy
from cinder import quota
from cinder import units
from cinder import utils
from cinder.openstack.common import excutils
from cinder.openstack.common import log as logging
from cinder.openstack.common.notifier import api as notifier
from cinder.openstack.common import timeutils
from cinder.volume import utils as volume_utils
from cinder.volume import volume_types
from cinder.taskflow import decorators
from cinder.taskflow.patterns import linear_flow
from cinder.taskflow import task
LOG = logging.getLogger(__name__)
ACTION = 'volume:create'
CONF = cfg.CONF
GB = units.GiB
QUOTAS = quota.QUOTAS
# Only in these 'sources' status can we attempt to create a volume from a
# source volume or a source snapshot, other status states we can not create
# from, 'error' being the common example.
PROCEED_STATUS = ('available',)
# When a volume errors out we have the ability to save a piece of the exception
# that caused said failure, but we don't want to save the whole message since
# that could be very large, just save up to this number of characters.
REASON_LENGTH = 128
# These attributes we will attempt to save for the volume if they exist
# in the source image metadata.
IMAGE_ATTRIBUTES = (
'checksum',
'container_format',
'disk_format',
'min_disk',
'min_ram',
'size',
)
def _make_pretty_name(method):
"""Makes a pretty name for a function/method."""
meth_pieces = [method.__name__]
# If its an instance method attempt to tack on the class name
if hasattr(method, 'im_self') and method.im_self is not None:
try:
meth_pieces.insert(0, method.im_self.__class__.__name__)
except AttributeError:
pass
return ".".join(meth_pieces)
def _find_result_spec(flow):
"""Find the last task that produced a valid volume_spec and returns it."""
for there_result in flow.results.values():
if not there_result or not 'volume_spec' in there_result:
continue
if there_result['volume_spec']:
return there_result['volume_spec']
return None
def _make_task_name(klass, addons=None):
"""Makes a pretty name for a task class."""
components = [klass.__module__, klass.__name__]
if addons:
for a in addons:
components.append(str(a))
return "%s#%s" % (ACTION, ".".join(components))
def _restore_source_status(context, db, volume_spec):
# NOTE(harlowja): Only if the type of the volume that was being created is
# the source volume type should we try to reset the source volume status
# back to its original value.
if not volume_spec or volume_spec.get('type') != 'source_vol':
return
source_volid = volume_spec['source_volid']
source_status = volume_spec['source_volstatus']
try:
LOG.debug(_('Restoring source %(source_volid)s status to %(status)s') %
{'status': source_status, 'source_volid': source_volid})
db.volume_update(context, source_volid, {'status': source_status})
except exception.CinderException:
# NOTE(harlowja): Don't let this cause further exceptions since this is
# a non-critical failure.
LOG.exception(_("Failed setting source volume %(source_volid)s back to"
" its initial %(source_status)s status") %
{'source_status': source_status,
'source_volid': source_volid})
def _error_out_volume(context, db, volume_id, reason=None):
def _clean_reason(reason):
if reason is None:
return '???'
reason = str(reason)
if len(reason) <= REASON_LENGTH:
return reason
else:
return reason[0:REASON_LENGTH] + '...'
update = {
'status': 'error',
}
reason = _clean_reason(reason)
# TODO(harlowja): re-enable when we can support this in the database.
# if reason:
# status['details'] = reason
try:
LOG.debug(_('Updating volume: %(volume_id)s with %(update)s'
' due to: %(reason)s') % {'volume_id': volume_id,
'reason': reason,
'update': update})
db.volume_update(context, volume_id, update)
except exception.CinderException:
# Don't let this cause further exceptions.
LOG.exception(_("Failed updating volume %(volume_id)s with"
" %(update)s") % {'volume_id': volume_id,
'update': update})
class CinderTask(task.Task):
"""The root task class for all cinder tasks.
It automatically names the given task using the module and class that
implement the given task as the task name.
TODO(harlowja): this likely should be moved later to a common folder in the
future when more of cinders flows are implemented.
"""
def __init__(self, addons=None):
super(CinderTask, self).__init__(_make_task_name(self.__class__,
addons))
class ValuesInjectTask(CinderTask):
"""This injects a dict into the flow.
This injection is done so that the keys (and values) provided can be
dependended on by tasks further down the line. Since taskflow is dependency
based this can be considered the bootstrapping task that provides an
initial set of values for other tasks to get started with. If this did not
exist then tasks would fail locating there dependent tasks and the values
said dependent tasks produce.
Reversion strategy: N/A
"""
def __init__(self, inject_what):
super(ValuesInjectTask, self).__init__()
self.provides.update(inject_what.keys())
self._inject = inject_what
def __call__(self, context):
return dict(self._inject)
class ExtractVolumeRequestTask(CinderTask):
"""Processes an api request values into a validated set of values.
This tasks responsibility is to take in a set of inputs that will form
a potential volume request and validates those values against a set of
conditions and/or translates those values into a valid set and then returns
the validated/translated values for use by other tasks.
Reversion strategy: N/A
"""
def __init__(self, image_service, az_check_functor=None):
super(ExtractVolumeRequestTask, self).__init__()
# This task will produce the following outputs (said outputs can be
# saved to durable storage in the future so that the flow can be
# reconstructed elsewhere and continued).
self.provides.update(['availability_zone', 'size', 'snapshot_id',
'source_volid', 'volume_type', 'volume_type_id',
'encryption_key_id'])
# This task requires the following inputs to operate (provided
# automatically to __call__(). This is done so that the flow can
# be reconstructed elsewhere and continue running (in the future).
#
# It also is used to be able to link tasks that produce items to tasks
# that consume items (thus allowing the linking of the flow to be
# mostly automatic).
self.requires.update(['availability_zone', 'image_id', 'metadata',
'size', 'snapshot', 'source_volume',
'volume_type', 'key_manager',
'backup_source_volume'])
self.image_service = image_service
self.az_check_functor = az_check_functor
if not self.az_check_functor:
self.az_check_functor = lambda az: True
@staticmethod
def _extract_snapshot(snapshot):
"""Extracts the snapshot id from the provided snapshot (if provided).
This function validates the input snapshot dict and checks that the
status of that snapshot is valid for creating a volume from.
"""
snapshot_id = None
if snapshot is not None:
if snapshot['status'] not in PROCEED_STATUS:
msg = _("Originating snapshot status must be one"
" of %s values")
msg = msg % (", ".join(PROCEED_STATUS))
# TODO(harlowja): what happens if the status changes after this
# initial snapshot status check occurs??? Seems like someone
# could delete the snapshot after this check passes but before
# the volume is offically created?
raise exception.InvalidSnapshot(reason=msg)
snapshot_id = snapshot['id']
return snapshot_id
@staticmethod
def _extract_source_volume(source_volume):
"""Extracts the volume id from the provided volume (if provided).
This function validates the input source_volume dict and checks that
the status of that source_volume is valid for creating a volume from.
"""
source_volid = None
if source_volume is not None:
if source_volume['status'] not in PROCEED_STATUS:
msg = _("Unable to create a volume from an originating source"
" volume when its status is not one of %s"
" values")
msg = msg % (", ".join(PROCEED_STATUS))
# TODO(harlowja): what happens if the status changes after this
# initial volume status check occurs??? Seems like someone
# could delete the volume after this check passes but before
# the volume is offically created?
raise exception.InvalidVolume(reason=msg)
source_volid = source_volume['id']
return source_volid
@staticmethod
def _extract_size(size, source_volume, snapshot):
"""Extracts and validates the volume size.
This function will validate or when not provided fill in the provided
size variable from the source_volume or snapshot and then does
validation on the size that is found and returns said validated size.
"""
def validate_snap_size(size):
if snapshot and size < snapshot['volume_size']:
msg = _("Volume size %(size)s cannot be lesser than"
" the snapshot size %(snap_size)s. "
"They must be >= original snapshot size.")
msg = msg % {'size': size,
'snap_size': snapshot['volume_size']}
raise exception.InvalidInput(reason=msg)
def validate_source_size(size):
if source_volume and size < source_volume['size']:
msg = _("Clones currently disallowed when "
"%(size)s < %(source_size)s. "
"They must be >= original volume size.")
msg = msg % {'size': size,
'source_size': source_volume['size']}
raise exception.InvalidInput(reason=msg)
def validate_int(size):
if not isinstance(size, int) or size <= 0:
msg = _("Volume size %(size)s must be an integer and"
" greater than 0") % {'size': size}
raise exception.InvalidInput(reason=msg)
# Figure out which validation functions we should be applying
# on the size value that we extract.
validator_functors = [validate_int]
if source_volume:
validator_functors.append(validate_source_size)
elif snapshot:
validator_functors.append(validate_snap_size)
# If the size is not provided then try to provide it.
if not size and source_volume:
size = source_volume['size']
elif not size and snapshot:
size = snapshot['volume_size']
size = utils.as_int(size)
LOG.debug("Validating volume %(size)s using %(functors)s" %
{'size': size,
'functors': ", ".join([_make_pretty_name(func)
for func in validator_functors])})
for func in validator_functors:
func(size)
return size
def _check_image_metadata(self, context, image_id, size):
"""Checks image existence and validates that the image metadata."""
# Check image existence
if not image_id:
return
# NOTE(harlowja): this should raise an error if the image does not
# exist, this is expected as it signals that the image_id is missing.
image_meta = self.image_service.show(context, image_id)
# Check image size is not larger than volume size.
image_size = utils.as_int(image_meta['size'], quiet=False)
image_size_in_gb = (image_size + GB - 1) / GB
if image_size_in_gb > size:
msg = _('Size of specified image %(image_size)s'
' is larger than volume size %(volume_size)s.')
msg = msg % {'image_size': image_size_in_gb, 'volume_size': size}
raise exception.InvalidInput(reason=msg)
# Check image min_disk requirement is met for the particular volume
min_disk = image_meta.get('min_disk', 0)
if size < min_disk:
msg = _('Image minDisk size %(min_disk)s is larger'
' than the volume size %(volume_size)s.')
msg = msg % {'min_disk': min_disk, 'volume_size': size}
raise exception.InvalidInput(reason=msg)
@staticmethod
def _check_metadata_properties(metadata=None):
"""Checks that the volume metadata properties are valid."""
if not metadata:
metadata = {}
for (k, v) in metadata.iteritems():
if len(k) == 0:
msg = _("Metadata property key blank")
LOG.warn(msg)
raise exception.InvalidVolumeMetadata(reason=msg)
if len(k) > 255:
msg = _("Metadata property key %s greater than 255 "
"characters") % k
LOG.warn(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
if len(v) > 255:
msg = _("Metadata property key %s value greater than"
" 255 characters") % k
LOG.warn(msg)
raise exception.InvalidVolumeMetadataSize(reason=msg)
def _extract_availability_zone(self, availability_zone, snapshot,
source_volume):
"""Extracts and returns a validated availability zone.
This function will extract the availability zone (if not provided) from
the snapshot or source_volume and then performs a set of validation
checks on the provided or extracted availability zone and then returns
the validated availability zone.
"""
# Try to extract the availability zone from the corresponding snapshot
# or source volume if either is valid so that we can be in the same
# availability zone as the source.
if availability_zone is None:
if snapshot:
try:
availability_zone = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if source_volume and availability_zone is None:
try:
availability_zone = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if availability_zone is None:
availability_zone = CONF.storage_availability_zone
if not self.az_check_functor(availability_zone):
msg = _("Availability zone '%s' is invalid") % (availability_zone)
LOG.warn(msg)
raise exception.InvalidInput(reason=msg)
# If the configuration only allows cloning to the same availability
# zone then we need to enforce that.
if CONF.cloned_volume_same_az:
snap_az = None
try:
snap_az = snapshot['volume']['availability_zone']
except (TypeError, KeyError):
pass
if snap_az and snap_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the snapshot")
raise exception.InvalidInput(reason=msg)
source_vol_az = None
try:
source_vol_az = source_volume['availability_zone']
except (TypeError, KeyError):
pass
if source_vol_az and source_vol_az != availability_zone:
msg = _("Volume must be in the same "
"availability zone as the source volume")
raise exception.InvalidInput(reason=msg)
return availability_zone
def _get_encryption_key_id(self, key_manager, context, volume_type_id,
snapshot, source_volume, backup_source_volume):
encryption_key_id = None
if volume_types.is_encrypted(context, volume_type_id):
if snapshot is not None: # creating from snapshot
encryption_key_id = snapshot['encryption_key_id']
elif source_volume is not None: # cloning volume
encryption_key_id = source_volume['encryption_key_id']
elif backup_source_volume is not None: # creating from backup
encryption_key_id = backup_source_volume['encryption_key_id']
# NOTE(joel-coffman): References to the encryption key should *not*
# be copied because the key is deleted when the volume is deleted.
# Clone the existing key and associate a separate -- but
# identical -- key with each volume.
if encryption_key_id is not None:
encryption_key_id = key_manager.copy_key(context,
encryption_key_id)
else:
encryption_key_id = key_manager.create_key(context)
return encryption_key_id
def _get_volume_type_id(self, volume_type, source_volume, snapshot,
backup_source_volume):
volume_type_id = None
if not volume_type and source_volume:
volume_type_id = source_volume['volume_type_id']
elif snapshot is not None:
if volume_type:
current_volume_type_id = volume_type.get('id')
if (current_volume_type_id !=
snapshot['volume_type_id']):
msg = _("Volume type will be changed to "
"be the same as the source volume.")
LOG.warn(msg)
volume_type_id = snapshot['volume_type_id']
elif backup_source_volume is not None:
volume_type_id = backup_source_volume['volume_type_id']
else:
volume_type_id = volume_type.get('id')
return volume_type_id
def __call__(self, context, size, snapshot, image_id, source_volume,
availability_zone, volume_type, metadata,
key_manager, backup_source_volume):
utils.check_exclusive_options(snapshot=snapshot,
imageRef=image_id,
source_volume=source_volume)
policy.enforce_action(context, ACTION)
# TODO(harlowja): what guarantee is there that the snapshot or source
# volume will remain available after we do this initial verification??
snapshot_id = self._extract_snapshot(snapshot)
source_volid = self._extract_source_volume(source_volume)
size = self._extract_size(size, source_volume, snapshot)
self._check_image_metadata(context, image_id, size)
availability_zone = self._extract_availability_zone(availability_zone,
snapshot,
source_volume)
# TODO(joel-coffman): This special handling of snapshots to ensure that
# their volume type matches the source volume is too convoluted. We
# should copy encryption metadata from the encrypted volume type to the
# volume upon creation and propogate that information to each snapshot.
# This strategy avoid any dependency upon the encrypted volume type.
if not volume_type and not source_volume and not snapshot:
volume_type = volume_types.get_default_volume_type()
volume_type_id = self._get_volume_type_id(volume_type,
source_volume, snapshot,
backup_source_volume)
encryption_key_id = self._get_encryption_key_id(key_manager,
context,
volume_type_id,
snapshot,
source_volume,
backup_source_volume)
self._check_metadata_properties(metadata)
return {
'size': size,
'snapshot_id': snapshot_id,
'source_volid': source_volid,
'availability_zone': availability_zone,
'volume_type': volume_type,
'volume_type_id': volume_type_id,
'encryption_key_id': encryption_key_id,
}
class EntryCreateTask(CinderTask):
"""Creates an entry for the given volume creation in the database.
Reversion strategy: remove the volume_id created from the database.
"""
def __init__(self, db):
super(EntryCreateTask, self).__init__()
self.db = db
self.requires.update(['availability_zone', 'description', 'metadata',
'name', 'reservations', 'size', 'snapshot_id',
'source_volid', 'volume_type_id',
'encryption_key_id'])
self.provides.update(['volume_properties', 'volume_id'])
def __call__(self, context, **kwargs):
"""Creates a database entry for the given inputs and returns details.
Accesses the database and creates a new entry for the to be created
volume using the given volume properties which are extracted from the
input kwargs (and associated requirements this task needs). These
requirements should be previously satisifed and validated by a
pre-cursor task.
"""
volume_properties = {
'size': kwargs.pop('size'),
'user_id': context.user_id,
'project_id': context.project_id,
'status': 'creating',
'attach_status': 'detached',
'encryption_key_id': kwargs.pop('encryption_key_id'),
# Rename these to the internal name.
'display_description': kwargs.pop('description'),
'display_name': kwargs.pop('name'),
}
# Merge in the other required arguments which should provide the rest
# of the volume property fields (if applicable).
volume_properties.update(kwargs)
volume = self.db.volume_create(context, volume_properties)
return {
'volume_id': volume['id'],
'volume_properties': volume_properties,
# NOTE(harlowja): it appears like further usage of this volume
# result actually depend on it being a sqlalchemy object and not
# just a plain dictionary so thats why we are storing this here.
#
# In the future where this task results can be serialized and
# restored automatically for continued running we will need to
# resolve the serialization & recreation of this object since raw
# sqlalchemy objects can't be serialized.
'volume': volume,
}
def revert(self, context, result, cause):
# We never produced a result and therefore can't destroy anything.
if not result:
return
vol_id = result['volume_id']
try:
self.db.volume_destroy(context, vol_id)
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
#
# NOTE(harlowja): Being unable to destroy a volume is pretty
# bad though!!
LOG.exception(_("Failed destroying volume entry %s"), vol_id)
class QuotaReserveTask(CinderTask):
"""Reserves a single volume with the given size & the given volume type.
Reversion strategy: rollback the quota reservation.
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or commited
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
def __init__(self):
super(QuotaReserveTask, self).__init__()
self.requires.update(['size', 'volume_type_id'])
self.provides.update(['reservations'])
def __call__(self, context, size, volume_type_id):
try:
reserve_opts = {'volumes': 1, 'gigabytes': size}
QUOTAS.add_volume_type_opts(context, reserve_opts, volume_type_id)
reservations = QUOTAS.reserve(context, **reserve_opts)
return {
'reservations': reservations,
}
except exception.OverQuota as e:
overs = e.kwargs['overs']
quotas = e.kwargs['quotas']
usages = e.kwargs['usages']
def _consumed(name):
return (usages[name]['reserved'] + usages[name]['in_use'])
def _is_over(name):
for over in overs:
if name in over:
return True
return False
if _is_over('gigabytes'):
msg = _("Quota exceeded for %(s_pid)s, tried to create "
"%(s_size)sG volume (%(d_consumed)dG "
"of %(d_quota)dG already consumed)")
LOG.warn(msg % {'s_pid': context.project_id,
's_size': size,
'd_consumed': _consumed('gigabytes'),
'd_quota': quotas['gigabytes']})
raise exception.VolumeSizeExceedsAvailableQuota()
elif _is_over('volumes'):
msg = _("Quota exceeded for %(s_pid)s, tried to create "
"volume (%(d_consumed)d volumes "
"already consumed)")
LOG.warn(msg % {'s_pid': context.project_id,
'd_consumed': _consumed('volumes')})
allowed = quotas['volumes']
raise exception.VolumeLimitExceeded(allowed=quotas['volumes'])
else:
# If nothing was reraised, ensure we reraise the initial error
raise
def revert(self, context, result, cause):
# We never produced a result and therefore can't destroy anything.
if not result:
return
# We actually produced an output that we can revert so lets attempt
# to use said output to rollback the reservation.
reservations = result['reservations']
try:
QUOTAS.rollback(context, reservations)
except exception.CinderException:
# We are already reverting, therefore we should silence this
# exception since a second exception being active will be bad.
LOG.exception(_("Failed rolling back quota for"
" %s reservations"), reservations)
class QuotaCommitTask(CinderTask):
"""Commits the reservation.
Reversion strategy: N/A (the rollback will be handled by the task that did
the initial reservation (see: QuotaReserveTask).
Warning Warning: if the process that is running this reserve and commit
process fails (or is killed before the quota is rolled back or commited
it does appear like the quota will never be rolled back). This makes
software upgrades hard (inflight operations will need to be stopped or
allowed to complete before the upgrade can occur). *In the future* when
taskflow has persistence built-in this should be easier to correct via
an automated or manual process.
"""
def __init__(self):
super(QuotaCommitTask, self).__init__()
self.requires.update(['reservations'])
def __call__(self, context, reservations):
QUOTAS.commit(context, reservations)
class VolumeCastTask(CinderTask):
"""Performs a volume create cast to the scheduler or to the volume manager.
This which will signal a transition of the api workflow to another child
and/or related workflow on another component.
Reversion strategy: N/A
"""
def __init__(self, scheduler_rpcapi, volume_rpcapi, db):
super(VolumeCastTask, self).__init__()
self.volume_rpcapi = volume_rpcapi
self.scheduler_rpcapi = scheduler_rpcapi
self.db = db
self.requires.update(['image_id', 'scheduler_hints', 'snapshot_id',
'source_volid', 'volume_id', 'volume_type',
'volume_properties'])
def _cast_create_volume(self, context, request_spec, filter_properties):
# NOTE(Rongze Zhu): A simple solution for bug 1008866.
#
# If snapshot_id is set, make the call create volume directly to
# the volume host where the snapshot resides instead of passing it
# through the scheduler. So snapshot can be copy to new volume.
source_volid = request_spec['source_volid']
volume_id = request_spec['volume_id']
snapshot_id = request_spec['snapshot_id']
image_id = request_spec['image_id']
host = None
if snapshot_id and CONF.snapshot_same_host:
snapshot_ref = self.db.snapshot_get(context, snapshot_id)
source_volume_ref = self.db.volume_get(context,
snapshot_ref['volume_id'])
host = source_volume_ref['host']
elif source_volid:
source_volume_ref = self.db.volume_get(context, source_volid)
host = source_volume_ref['host']
if not host:
# Cast to the scheduler and let it handle whatever is needed
# to select the target host for this volume.
self.scheduler_rpcapi.create_volume(
context,
CONF.volume_topic,
volume_id,
snapshot_id,
image_id,
request_spec=request_spec,
filter_properties=filter_properties)
else:
# Bypass the scheduler and send the request directly to the volume
# manager.
now = timeutils.utcnow()
values = {'host': host, 'scheduled_at': now}
volume_ref = self.db.volume_update(context, volume_id, values)
self.volume_rpcapi.create_volume(
context,
volume_ref,
volume_ref['host'],
request_spec=request_spec,
filter_properties=filter_properties,
allow_reschedule=False,
snapshot_id=snapshot_id,
image_id=image_id,
source_volid=source_volid)
def __call__(self, context, **kwargs):
scheduler_hints = kwargs.pop('scheduler_hints', None)
request_spec = kwargs.copy()
filter_properties = {}
if scheduler_hints:
filter_properties['scheduler_hints'] = scheduler_hints
self._cast_create_volume(context, request_spec, filter_properties)
class OnFailureChangeStatusTask(CinderTask):
"""Helper task that sets a volume id to status error.
Reversion strategy: On failure of any flow that includes this task the
volume id that is associated with this task will be have its status set
to error. If a volume specification is provided and the type of that spec
is a source volume said source volume will have its status status updated
as well.
"""
def __init__(self, db):
super(OnFailureChangeStatusTask, self).__init__()
self.db = db
self.requires.update(['volume_id'])
self.optional.update(['volume_spec'])
def __call__(self, context, volume_id, volume_spec=None):
# Save these items since we only use them if a reversion is triggered.
return {
'volume_id': volume_id,
'volume_spec': volume_spec,
}
def revert(self, context, result, cause):
volume_spec = result.get('volume_spec')
if not volume_spec:
# Attempt to use it from a later task that *should* have populated
# this from the database. It is not needed to be found since
# reverting will continue without it.
volume_spec = _find_result_spec(cause.flow)
# Restore the source volume status and set the volume to error status.
volume_id = result['volume_id']
_restore_source_status(context, self.db, volume_spec)
_error_out_volume(context, self.db, volume_id, reason=cause.exc)
LOG.error(_("Volume %s: create failed"), volume_id)
exc_info = False
if all(cause.exc_info):
exc_info = cause.exc_info
LOG.error(_('Unexpected build error:'), exc_info=exc_info)
class OnFailureRescheduleTask(CinderTask):
"""Triggers a rescheduling request to be sent when reverting occurs.
Reversion strategy: Triggers the rescheduling mechanism whereby a cast gets
sent to the scheduler rpc api to allow for an attempt X of Y for scheduling
this volume elsewhere.
"""
def __init__(self, reschedule_context, db, scheduler_rpcapi):
super(OnFailureRescheduleTask, self).__init__()
self.requires.update(['filter_properties', 'image_id', 'request_spec',
'snapshot_id', 'volume_id'])
self.optional.update(['volume_spec'])
self.scheduler_rpcapi = scheduler_rpcapi
self.db = db
self.reschedule_context = reschedule_context
# These exception types will trigger the volume to be set into error
# status rather than being rescheduled.
self.no_reschedule_types = [
# The volume has already finished being created when the exports
# occur, rescheduling would be bad if it happened due to exports
# not succeeding.
exception.ExportFailure,
# Image copying happens after volume creation so rescheduling due
# to copy failure will mean the same volume will be created at
# another place when it still exists locally.
exception.ImageCopyFailure,
# Metadata updates happen after the volume has been created so if
# they fail, rescheduling will likely attempt to create the volume
# on another machine when it still exists locally.
exception.MetadataCopyFailure,
exception.MetadataCreateFailure,
exception.MetadataUpdateFailure,
# The volume/snapshot has been removed from the database, that
# can not be fixed by rescheduling.
exception.VolumeNotFound,
exception.SnapshotNotFound,
exception.VolumeTypeNotFound,
exception.ImageUnacceptable,
]
def _is_reschedulable(self, cause):
(exc_type, value, traceback) = cause.exc_info
if not exc_type and cause.exc:
exc_type = type(cause.exc)
if not exc_type:
return True
if exc_type in self.no_reschedule_types:
return False
return True
def __call__(self, context, *args, **kwargs):
# Save these items since we only use them if a reversion is triggered.
return kwargs.copy()
def _reschedule(self, context, cause, request_spec, filter_properties,
snapshot_id, image_id, volume_id, **kwargs):
"""Actions that happen during the rescheduling attempt occur here."""
create_volume = self.scheduler_rpcapi.create_volume
if not filter_properties:
filter_properties = {}
if 'retry' not in filter_properties:
filter_properties['retry'] = {}
retry_info = filter_properties['retry']
num_attempts = retry_info.get('num_attempts', 0)
request_spec['volume_id'] = volume_id
LOG.debug(_("Volume %(volume_id)s: re-scheduling %(method)s "
"attempt %(num)d due to %(reason)s") %
{'volume_id': volume_id,
'method': _make_pretty_name(create_volume),
'num': num_attempts, 'reason': unicode(cause.exc)})
if all(cause.exc_info):
# Stringify to avoid circular ref problem in json serialization
retry_info['exc'] = traceback.format_exception(*cause.exc_info)
return create_volume(context, CONF.volume_topic, volume_id,
snapshot_id, image_id, request_spec,
filter_properties)
def _post_reschedule(self, context, volume_id):
"""Actions that happen after the rescheduling attempt occur here."""
LOG.debug(_("Volume %s: re-scheduled"), volume_id)
def _pre_reschedule(self, context, volume_id):
"""Actions that happen before the rescheduling attempt occur here."""
try:
# Reset the volume state.
#
# NOTE(harlowja): this is awkward to be done here, shouldn't
# this happen at the scheduler itself and not before it gets
# sent to the scheduler? (since what happens if it never gets
# there??). It's almost like we need a status of 'on-the-way-to
# scheduler' in the future.
update = {
'status': 'creating',
'scheduled_at': timeutils.utcnow(),
}
LOG.debug(_("Updating volume %(volume_id)s with %(update)s") %
{'update': update, 'volume_id': volume_id})
self.db.volume_update(context, volume_id, update)
except exception.CinderException:
# Don't let resetting the status cause the rescheduling to fail.
LOG.exception(_("Volume %s: resetting 'creating' status failed"),
volume_id)
def revert(self, context, result, cause):
volume_spec = result.get('volume_spec')
if not volume_spec:
# Find it from a prior task that populated this from the database.
volume_spec = _find_result_spec(cause.flow)
volume_id = result['volume_id']
# Use a different context when rescheduling.
if self.reschedule_context:
context = self.reschedule_context
# If we are now supposed to reschedule (or unable to), then just
# restore the source volume status and set the volume to error status.
def do_error_revert():
LOG.debug(_("Failing volume %s creation by altering volume status"
" instead of rescheduling"), volume_id)
_restore_source_status(context, self.db, volume_spec)
_error_out_volume(context, self.db, volume_id, reason=cause.exc)
LOG.error(_("Volume %s: create failed"), volume_id)
# Check if we have a cause which can tell us not to reschedule.
if not self._is_reschedulable(cause):
do_error_revert()
else:
try:
self._pre_reschedule(context, volume_id)
self._reschedule(context, cause, **result)
self._post_reschedule(context, volume_id)
except exception.CinderException:
LOG.exception(_("Volume %s: rescheduling failed"), volume_id)
# NOTE(harlowja): Do error volume status changing instead.
do_error_revert()
exc_info = False
if all(cause.exc_info):
exc_info = cause.exc_info
LOG.error(_('Unexpected build error:'), exc_info=exc_info)
class NotifySchedulerFailureTask(CinderTask):
"""Helper task that notifies some external service on failure.
Reversion strategy: On failure of any flow that includes this task the
request specification associated with that flow will be extracted and
sent as a payload to the notification service under the given methods
scheduler topic.
"""
def __init__(self, method):
super(NotifySchedulerFailureTask, self).__init__()
self.requires.update(['request_spec', 'volume_id'])
self.method = method
self.topic = 'scheduler.%s' % self.method
self.publisher_id = notifier.publisher_id("scheduler")
def __call__(self, context, **kwargs):
# Save these items since we only use them if a reversion is triggered.
return kwargs.copy()
def revert(self, context, result, cause):
request_spec = result['request_spec']
volume_id = result['volume_id']
volume_properties = request_spec['volume_properties']
payload = {
'request_spec': request_spec,
'volume_properties': volume_properties,