/
api.py
3993 lines (3440 loc) · 177 KB
/
api.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 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2015 Tom Barron. All rights reserved.
# Copyright (c) 2015 Mirantis Inc.
#
# 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.
"""
Handles all requests relating to shares.
"""
import functools
import json
from oslo_config import cfg
from oslo_log import log
from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
from manila.api import common as api_common
from manila.common import constants
from manila import context as manila_context
from manila import coordination
from manila.data import rpcapi as data_rpcapi
from manila.db import base
from manila import exception
from manila.i18n import _
from manila import policy
from manila import quota
from manila.scheduler import rpcapi as scheduler_rpcapi
from manila.share import access
from manila.share import rpcapi as share_rpcapi
from manila.share import share_types
from manila.share import utils as share_utils
from manila import utils
share_api_opts = [
cfg.BoolOpt('use_scheduler_creating_share_from_snapshot',
default=False,
help='If set to False, then share creation from snapshot will '
'be performed on the same host. '
'If set to True, then scheduler will be used.'
'When enabling this option make sure that filter '
'CreateFromSnapshotFilter is enabled and to have hosts '
'reporting replication_domain option.'
)
]
CONF = cfg.CONF
CONF.register_opts(share_api_opts)
LOG = log.getLogger(__name__)
GB = 1048576 * 1024
QUOTAS = quota.QUOTAS
AFFINITY_HINT = 'same_host'
ANTI_AFFINITY_HINT = 'different_host'
AFFINITY_KEY = "__affinity_same_host"
ANTI_AFFINITY_KEY = "__affinity_different_host"
def locked_security_service_update_operation(operation):
"""Lock decorator for security service operation.
Takes a named lock prior to executing the operation. The lock is named with
the ids of the security services.
"""
def wrapped(*args, **kwargs):
new_id = kwargs.get('new_security_service_id', '')
current_id = kwargs.get('current_security_service_id', '')
@coordination.synchronized(
'locked-security-service-update-operation-%(new)s-%(curr)s' % {
'new': new_id,
'curr': current_id,
})
def locked_security_service_operation(*_args, **_kwargs):
return operation(*_args, **_kwargs)
return locked_security_service_operation(*args, **kwargs)
return wrapped
def locked_share_server_update_allocations_operation(operation):
"""Lock decorator for share server update allocations operation.
Takes a named lock prior to executing the operation. The lock is named with
the ids of the share network and the region to be updated.
"""
def wrapped(*args, **kwargs):
az_id = kwargs.get('availability_zone_id')
share_net_id = kwargs.get('share_network_id')
@coordination.synchronized(
'locked-share-server-update-allocations-operation-%(net)s-%(az)s'
% {
'net': share_net_id,
'az': az_id,
})
def locked_share_server_allocations_operation(*_args, **_kwargs):
return operation(*_args, **_kwargs)
return locked_share_server_allocations_operation(*args, **kwargs)
return wrapped
class API(base.Base):
"""API for interacting with the share manager."""
def __init__(self, db_driver=None):
super(API, self).__init__(db_driver)
self.scheduler_rpcapi = scheduler_rpcapi.SchedulerAPI()
self.share_rpcapi = share_rpcapi.ShareAPI()
self.access_helper = access.ShareInstanceAccess(self.db, None)
coordination.LOCK_COORDINATOR.start()
def prevent_locked_action_on_share(arg):
"""Decorator for preventing a locked method from executing on a share.
Add this decorator to any API method which takes a RequestContext
object as a first parameter and a share object as the second
parameter.
Can be used in any of the following forms
@prevent_locked_action_on_share
@prevent_locked_action_on_share('my_action_name')
:param arg: Can either be the function being decorated or a str
containing the 'action' that we need to check resource locks for.
If no action name is provided, the function name is assumed to be
the action name.
"""
action_name = None
def check_for_locks(f):
@functools.wraps(f)
def wrapper(self, context, share, *args, **kwargs):
action = action_name or f.__name__
resource_locks, __ = (
self.db.resource_lock_get_all(
context.elevated(),
filters={'resource_id': share['id'],
'resource_action': action,
'all_projects': True},
)
)
if resource_locks:
msg_payload = {
'locks': ', '.join(
[lock['id'] for lock in resource_locks]
),
'action': action,
}
msg = (f"Resource lock/s [{msg_payload['locks']}] "
f"prevent {action} action.")
raise exception.InvalidShare(msg)
return f(self, context, share, *args, **kwargs)
return wrapper
if callable(arg):
return check_for_locks(arg)
else:
action_name = arg
return check_for_locks
def _get_all_availability_zones_with_subnets(self, context,
share_network_id):
compatible_azs_name = []
compatible_azs_multiple = {}
for az in self.db.availability_zone_get_all(context):
subnets = (
self.db.share_network_subnets_get_all_by_availability_zone_id(
context, share_network_id=share_network_id,
availability_zone_id=az['id']))
if subnets:
compatible_azs_multiple[az['id']] = len(subnets) > 1
compatible_azs_name.append(az['name'])
return compatible_azs_name, compatible_azs_multiple
@staticmethod
def check_if_share_quotas_exceeded(context, quota_exception,
share_size, operation='create'):
overs = quota_exception.kwargs['overs']
usages = quota_exception.kwargs['usages']
quotas = quota_exception.kwargs['quotas']
def _consumed(name):
return (usages[name]['reserved'] + usages[name]['in_use'])
if 'gigabytes' in overs:
LOG.warning("Quota exceeded for %(s_pid)s, "
"tried to %(operation)s "
"%(s_size)sG share (%(d_consumed)dG of "
"%(d_quota)dG already consumed).", {
's_pid': context.project_id,
's_size': share_size,
'd_consumed': _consumed('gigabytes'),
'd_quota': quotas['gigabytes'],
'operation': operation})
raise exception.ShareSizeExceedsAvailableQuota()
elif 'shares' in overs:
LOG.warning("Quota exceeded for %(s_pid)s, "
"tried to %(operation)s "
"share (%(d_consumed)d shares "
"already consumed).", {
's_pid': context.project_id,
'd_consumed': _consumed('shares'),
'operation': operation})
raise exception.ShareLimitExceeded(allowed=quotas['shares'])
@staticmethod
def check_if_replica_quotas_exceeded(context, quota_exception,
replica_size,
resource_type='share_replica'):
overs = quota_exception.kwargs['overs']
usages = quota_exception.kwargs['usages']
quotas = quota_exception.kwargs['quotas']
def _consumed(name):
return (usages[name]['reserved'] + usages[name]['in_use'])
if 'share_replicas' in overs:
LOG.warning("Quota exceeded for %(s_pid)s, "
"unable to create share-replica (%(d_consumed)d "
"of %(d_quota)d already consumed).", {
's_pid': context.project_id,
'd_consumed': _consumed('share_replicas'),
'd_quota': quotas['share_replicas']})
exception_kwargs = {}
if resource_type != 'share_replica':
msg = _("Failed while creating a share with replication "
"support. Maximum number of allowed share-replicas "
"is exceeded.")
exception_kwargs['message'] = msg
raise exception.ShareReplicasLimitExceeded(**exception_kwargs)
elif 'replica_gigabytes' in overs:
LOG.warning("Quota exceeded for %(s_pid)s, "
"unable to create a share replica size of "
"%(s_size)sG (%(d_consumed)dG of "
"%(d_quota)dG already consumed).", {
's_pid': context.project_id,
's_size': replica_size,
'd_consumed': _consumed('replica_gigabytes'),
'd_quota': quotas['replica_gigabytes']})
exception_kwargs = {}
if resource_type != 'share_replica':
msg = _("Failed while creating a share with replication "
"support. Requested share replica exceeds allowed "
"project/user or share type gigabytes quota.")
exception_kwargs['message'] = msg
raise exception.ShareReplicaSizeExceedsAvailableQuota(
**exception_kwargs)
def create(self, context, share_proto, size, name, description,
snapshot_id=None, availability_zone=None, metadata=None,
share_network_id=None, share_type=None, is_public=False,
share_group_id=None, share_group_snapshot_member=None,
availability_zones=None, scheduler_hints=None,
az_request_multiple_subnet_support_map=None):
"""Create new share."""
api_common.check_metadata_properties(metadata)
if snapshot_id is not None:
snapshot = self.get_snapshot(context, snapshot_id)
if snapshot['aggregate_status'] != constants.STATUS_AVAILABLE:
msg = _("status must be '%s'") % constants.STATUS_AVAILABLE
raise exception.InvalidShareSnapshot(reason=msg)
if not size:
size = snapshot['size']
else:
snapshot = None
if not strutils.is_int_like(size) or int(size) <= 0:
msg = (_("Share size '%s' must be an integer and greater than 0")
% size)
raise exception.InvalidInput(reason=msg)
# make sure size has been convert to int.
size = int(size)
if snapshot and size < snapshot['size']:
msg = (_("Share size '%s' must be equal or greater "
"than snapshot size") % size)
raise exception.InvalidInput(reason=msg)
# ensure we pass the share_type provisioning filter on size
share_types.provision_filter_on_size(context, share_type, size)
if snapshot is None:
share_type_id = share_type['id'] if share_type else None
else:
source_share = self.db.share_get(context, snapshot['share_id'])
source_share_az = source_share['instance']['availability_zone']
if availability_zone is None:
availability_zone = source_share_az
elif (availability_zone != source_share_az
and not CONF.use_scheduler_creating_share_from_snapshot):
LOG.error("The specified availability zone must be the same "
"as parent share when you have the configuration "
"option 'use_scheduler_creating_share_from_snapshot'"
" set to False.")
msg = _("The specified availability zone must be the same "
"as the parent share when creating from snapshot.")
raise exception.InvalidInput(reason=msg)
if share_type is None:
# Grab the source share's share_type if no new share type
# has been provided.
share_type_id = source_share['instance']['share_type_id']
share_type = share_types.get_share_type(context, share_type_id)
else:
share_type_id = share_type['id']
if share_type_id != source_share['instance']['share_type_id']:
msg = _("Invalid share type specified: the requested "
"share type must match the type of the source "
"share. If a share type is not specified when "
"requesting a new share from a snapshot, the "
"share type of the source share will be applied "
"to the new share.")
raise exception.InvalidInput(reason=msg)
supported_share_protocols = (
proto.upper() for proto in CONF.enabled_share_protocols)
if not (share_proto and
share_proto.upper() in supported_share_protocols):
msg = (_("Invalid share protocol provided: %(provided)s. "
"It is either disabled or unsupported. Available "
"protocols: %(supported)s") % dict(
provided=share_proto,
supported=CONF.enabled_share_protocols))
raise exception.InvalidInput(reason=msg)
self.check_is_share_size_within_per_share_quota_limit(context, size)
deltas = {'shares': 1, 'gigabytes': size}
share_type_attributes = self.get_share_attributes_from_share_type(
share_type)
share_type_supports_replication = share_type_attributes.get(
'replication_type', None)
if share_type_supports_replication:
deltas.update(
{'share_replicas': 1, 'replica_gigabytes': size})
try:
reservations = QUOTAS.reserve(
context, share_type_id=share_type_id, **deltas)
except exception.OverQuota as e:
self.check_if_share_quotas_exceeded(context, e, size)
if share_type_supports_replication:
self.check_if_replica_quotas_exceeded(context, e, size,
resource_type='share')
share_group = None
if share_group_id:
try:
share_group = self.db.share_group_get(context, share_group_id)
except exception.NotFound as e:
raise exception.InvalidParameterValue(e.message)
if (not share_group_snapshot_member and
not (share_group['status'] == constants.STATUS_AVAILABLE)):
params = {
'avail': constants.STATUS_AVAILABLE,
'status': share_group['status'],
}
msg = _("Share group status must be %(avail)s, got "
"%(status)s.") % params
raise exception.InvalidShareGroup(message=msg)
if share_type_id:
share_group_st_ids = [
st['share_type_id']
for st in share_group.get('share_types', [])]
if share_type_id not in share_group_st_ids:
params = {
'type': share_type_id,
'group': share_group_id,
}
msg = _("The specified share type (%(type)s) is not "
"supported by the specified share group "
"(%(group)s).") % params
raise exception.InvalidParameterValue(msg)
if not share_group.get('share_network_id') == share_network_id:
params = {
'net': share_network_id,
'group': share_group_id
}
msg = _("The specified share network (%(net)s) is not "
"supported by the specified share group "
"(%(group)s).") % params
raise exception.InvalidParameterValue(msg)
options = {
'size': size,
'user_id': context.user_id,
'project_id': context.project_id,
'snapshot_id': snapshot_id,
'metadata': metadata,
'display_name': name,
'display_description': description,
'share_proto': share_proto,
'is_public': is_public,
'share_group_id': share_group_id,
}
options.update(share_type_attributes)
if share_group_snapshot_member:
options['source_share_group_snapshot_member_id'] = (
share_group_snapshot_member['id'])
# NOTE(dviroel): If a target availability zone was not provided, the
# scheduler will receive a list with all availability zones that
# contains a subnet within the selected share network.
if share_network_id and not availability_zone:
compatible_azs_name, compatible_azs_multiple = (
self._get_all_availability_zones_with_subnets(
context, share_network_id))
if not availability_zones:
availability_zones = compatible_azs_name
else:
availability_zones = (
[az for az in availability_zones
if az in compatible_azs_name])
if not availability_zones:
msg = _(
"The share network is not supported within any requested "
"availability zone. Check the share type's "
"'availability_zones' extra-spec and the availability "
"zones of the share network subnets")
raise exception.InvalidInput(message=msg)
if az_request_multiple_subnet_support_map:
az_request_multiple_subnet_support_map.update(
compatible_azs_multiple)
else:
az_request_multiple_subnet_support_map = (
compatible_azs_multiple)
try:
share = self.db.share_create(context, options,
create_share_instance=False)
QUOTAS.commit(context, reservations, share_type_id=share_type_id)
except Exception:
with excutils.save_and_reraise_exception():
try:
self.db.share_delete(context, share['id'])
finally:
QUOTAS.rollback(
context, reservations, share_type_id=share_type_id)
self.save_scheduler_hints(context, share, scheduler_hints)
host = None
snapshot_host = None
if snapshot:
snapshot_host = snapshot['share']['instance']['host']
if not CONF.use_scheduler_creating_share_from_snapshot:
# Shares from snapshots with restriction - source host only.
# It is common situation for different types of backends.
host = snapshot['share']['instance']['host']
if share_group and host is None:
host = share_group['host']
self.create_instance(
context, share, share_network_id=share_network_id, host=host,
availability_zone=availability_zone, share_group=share_group,
share_group_snapshot_member=share_group_snapshot_member,
share_type_id=share_type_id, availability_zones=availability_zones,
snapshot_host=snapshot_host, scheduler_hints=scheduler_hints,
az_request_multiple_subnet_support_map=(
az_request_multiple_subnet_support_map))
# Retrieve the share with instance details
share = self.db.share_get(context, share['id'])
return share
def get_share_attributes_from_share_type(self, share_type):
"""Determine share attributes from the share type.
The share type can change any time after shares of that type are
created, so we copy some share type attributes to the share to
consistently govern the behavior of that share over its lifespan.
"""
inferred_map = constants.ExtraSpecs.INFERRED_OPTIONAL_MAP
snapshot_support_key = constants.ExtraSpecs.SNAPSHOT_SUPPORT
create_share_from_snapshot_key = (
constants.ExtraSpecs.CREATE_SHARE_FROM_SNAPSHOT_SUPPORT)
revert_to_snapshot_key = (
constants.ExtraSpecs.REVERT_TO_SNAPSHOT_SUPPORT)
mount_snapshot_support_key = (
constants.ExtraSpecs.MOUNT_SNAPSHOT_SUPPORT)
snapshot_support_default = inferred_map.get(snapshot_support_key)
create_share_from_snapshot_support_default = inferred_map.get(
create_share_from_snapshot_key)
revert_to_snapshot_support_default = inferred_map.get(
revert_to_snapshot_key)
mount_snapshot_support_default = inferred_map.get(
constants.ExtraSpecs.MOUNT_SNAPSHOT_SUPPORT)
if share_type:
snapshot_support = share_types.parse_boolean_extra_spec(
snapshot_support_key,
share_type.get('extra_specs', {}).get(
snapshot_support_key, snapshot_support_default))
create_share_from_snapshot_support = (
share_types.parse_boolean_extra_spec(
create_share_from_snapshot_key,
share_type.get('extra_specs', {}).get(
create_share_from_snapshot_key,
create_share_from_snapshot_support_default)))
revert_to_snapshot_support = (
share_types.parse_boolean_extra_spec(
revert_to_snapshot_key,
share_type.get('extra_specs', {}).get(
revert_to_snapshot_key,
revert_to_snapshot_support_default)))
mount_snapshot_support = share_types.parse_boolean_extra_spec(
mount_snapshot_support_key, share_type.get(
'extra_specs', {}).get(
mount_snapshot_support_key,
mount_snapshot_support_default))
replication_type = share_type.get('extra_specs', {}).get(
'replication_type')
else:
snapshot_support = snapshot_support_default
create_share_from_snapshot_support = (
create_share_from_snapshot_support_default)
revert_to_snapshot_support = revert_to_snapshot_support_default
mount_snapshot_support = mount_snapshot_support_default
replication_type = None
return {
'snapshot_support': snapshot_support,
'create_share_from_snapshot_support':
create_share_from_snapshot_support,
'revert_to_snapshot_support': revert_to_snapshot_support,
'replication_type': replication_type,
'mount_snapshot_support': mount_snapshot_support,
}
def create_instance(self, context, share, share_network_id=None,
host=None, availability_zone=None,
share_group=None, share_group_snapshot_member=None,
share_type_id=None, availability_zones=None,
snapshot_host=None, scheduler_hints=None,
az_request_multiple_subnet_support_map=None):
request_spec, share_instance = (
self.create_share_instance_and_get_request_spec(
context, share, availability_zone=availability_zone,
share_group=share_group, host=host,
share_network_id=share_network_id,
share_type_id=share_type_id,
availability_zones=availability_zones,
snapshot_host=snapshot_host,
az_request_multiple_subnet_support_map=(
az_request_multiple_subnet_support_map)))
if share_group_snapshot_member:
# Inherit properties from the share_group_snapshot_member
member_share_instance = share_group_snapshot_member[
'share_instance']
updates = {
'host': member_share_instance['host'],
'share_network_id': member_share_instance['share_network_id'],
'share_server_id': member_share_instance['share_server_id'],
}
share = self.db.share_instance_update(context,
share_instance['id'],
updates)
# NOTE(ameade): Do not cast to driver if creating from share group
# snapshot
return
if host:
self.share_rpcapi.create_share_instance(
context,
share_instance,
host,
request_spec=request_spec,
filter_properties={'scheduler_hints': scheduler_hints},
snapshot_id=share['snapshot_id'],
)
else:
# Create share instance from scratch or from snapshot could happen
# on hosts other than the source host.
self.scheduler_rpcapi.create_share_instance(
context,
request_spec=request_spec,
filter_properties={'scheduler_hints': scheduler_hints},
)
return share_instance
def create_share_instance_and_get_request_spec(
self, context, share, availability_zone=None,
share_group=None, host=None, share_network_id=None,
share_type_id=None, cast_rules_to_readonly=False,
availability_zones=None, snapshot_host=None,
az_request_multiple_subnet_support_map=None):
availability_zone_id = None
if availability_zone:
availability_zone_id = self.db.availability_zone_get(
context, availability_zone).id
# TODO(u_glide): Add here validation that provided share network
# doesn't conflict with provided availability_zone when Neutron
# will have AZ support.
share_instance = self.db.share_instance_create(
context, share['id'],
{
'share_network_id': share_network_id,
'status': constants.STATUS_CREATING,
'scheduled_at': timeutils.utcnow(),
'host': host if host else '',
'availability_zone_id': availability_zone_id,
'share_type_id': share_type_id,
'cast_rules_to_readonly': cast_rules_to_readonly,
}
)
share_properties = {
'id': share['id'],
'size': share['size'],
'user_id': share['user_id'],
'project_id': share['project_id'],
'metadata': self.db.share_metadata_get(context, share['id']),
'share_server_id': share_instance['share_server_id'],
'snapshot_support': share['snapshot_support'],
'create_share_from_snapshot_support':
share['create_share_from_snapshot_support'],
'revert_to_snapshot_support': share['revert_to_snapshot_support'],
'mount_snapshot_support': share['mount_snapshot_support'],
'share_proto': share['share_proto'],
'share_type_id': share_type_id,
'is_public': share['is_public'],
'share_group_id': share['share_group_id'],
'source_share_group_snapshot_member_id': share[
'source_share_group_snapshot_member_id'],
'snapshot_id': share['snapshot_id'],
'replication_type': share['replication_type'],
}
share_instance_properties = {
'id': share_instance['id'],
'availability_zone_id': share_instance['availability_zone_id'],
'share_network_id': share_instance['share_network_id'],
'share_server_id': share_instance['share_server_id'],
'share_id': share_instance['share_id'],
'host': share_instance['host'],
'status': share_instance['status'],
'replica_state': share_instance['replica_state'],
'share_type_id': share_instance['share_type_id'],
}
share_type = None
if share_instance['share_type_id']:
share_type = self.db.share_type_get(
context, share_instance['share_type_id'])
request_spec = {
'share_properties': share_properties,
'share_instance_properties': share_instance_properties,
'share_proto': share['share_proto'],
'share_id': share['id'],
'snapshot_id': share['snapshot_id'],
'snapshot_host': snapshot_host,
'share_type': share_type,
'share_group': share_group,
'availability_zone_id': availability_zone_id,
'availability_zones': availability_zones,
'az_request_multiple_subnet_support_map': (
az_request_multiple_subnet_support_map),
}
return request_spec, share_instance
def create_share_replica(self, context, share, availability_zone=None,
share_network_id=None, scheduler_hints=None):
parent_share_network_id = share.get('share_network_id')
if (parent_share_network_id and share_network_id and
parent_share_network_id != share_network_id):
parent_security_services = (
self.db.security_service_get_all_by_share_network(
context, parent_share_network_id))
security_services = (
self.db.security_service_get_all_by_share_network(
context, share_network_id))
parent_ss = set([s['id'] for s in parent_security_services])
ss = set([s['id'] for s in security_services])
if ss != parent_ss:
msg = _("Share and its replica can't be in "
"different authentication domains.")
raise exception.InvalidInput(reason=msg)
if not share.get('replication_type'):
msg = _("Replication not supported for share %s.")
raise exception.InvalidShare(message=msg % share['id'])
if share.get('share_group_id'):
msg = _("Replication not supported for shares in a group.")
raise exception.InvalidShare(message=msg)
if scheduler_hints:
if ('only_host' not in scheduler_hints.keys() or len(
scheduler_hints) > 1):
msg = _("Arg 'scheduler_hints' supports only 'only_host' key.")
raise exception.InvalidInput(reason=msg)
self._check_is_share_busy(share)
active_replica = self.db.share_replicas_get_available_active_replica(
context, share['id'])
if not active_replica:
msg = _("Share %s does not have any active replica in available "
"state.")
raise exception.ReplicationException(reason=msg % share['id'])
share_type = share_types.get_share_type(
context, share.instance['share_type_id'])
type_azs = share_type['extra_specs'].get('availability_zones', '')
type_azs = [t for t in type_azs.split(',') if type_azs]
if (availability_zone and type_azs and
availability_zone not in type_azs):
msg = _("Share replica cannot be created since the share type "
"%(type)s is not supported within the availability zone "
"chosen %(az)s.")
type_name = '%s' % (share_type['name'] or '')
type_id = '(ID: %s)' % share_type['id']
payload = {'type': '%s%s' % (type_name, type_id),
'az': availability_zone}
raise exception.InvalidShare(message=msg % payload)
try:
reservations = QUOTAS.reserve(
context, share_replicas=1, replica_gigabytes=share['size'],
share_type_id=share_type['id']
)
except exception.OverQuota as e:
self.check_if_replica_quotas_exceeded(context, e, share['size'])
az_request_multiple_subnet_support_map = {}
if share_network_id:
if availability_zone:
try:
az = self.db.availability_zone_get(context,
availability_zone)
except exception.AvailabilityZoneNotFound:
msg = _("Share replica cannot be created because the "
"specified availability zone does not exist.")
raise exception.InvalidInput(message=msg)
az_id = az.get('id')
subnets = (
self.db.
share_network_subnets_get_all_by_availability_zone_id(
context, share_network_id, az_id))
if not subnets:
msg = _("Share replica cannot be created because the "
"share network is not available within the "
"specified availability zone.")
raise exception.InvalidShare(message=msg)
az_request_multiple_subnet_support_map[az_id] = (
len(subnets) > 1)
else:
# NOTE(dviroel): If a target availability zone was not
# provided, the scheduler will receive a list with all
# availability zones that contains subnets within the
# selected share network.
compatible_azs_name, compatible_azs_multiple = (
self._get_all_availability_zones_with_subnets(
context, share_network_id))
if not type_azs:
type_azs = compatible_azs_name
else:
type_azs = (
[az for az in type_azs if az in compatible_azs_name])
if not type_azs:
msg = _(
"The share network is not supported within any "
"requested availability zone. Check the share type's "
"'availability_zones' extra-spec and the availability "
"zones of the share network subnets")
raise exception.InvalidInput(message=msg)
az_request_multiple_subnet_support_map.update(
compatible_azs_multiple)
if share['replication_type'] == constants.REPLICATION_TYPE_READABLE:
cast_rules_to_readonly = True
else:
cast_rules_to_readonly = False
try:
request_spec, share_replica = (
self.create_share_instance_and_get_request_spec(
context, share, availability_zone=availability_zone,
share_network_id=share_network_id,
share_type_id=share['instance']['share_type_id'],
cast_rules_to_readonly=cast_rules_to_readonly,
availability_zones=type_azs,
az_request_multiple_subnet_support_map=(
az_request_multiple_subnet_support_map))
)
QUOTAS.commit(
context, reservations, project_id=share['project_id'],
share_type_id=share_type['id'],
)
except Exception:
with excutils.save_and_reraise_exception():
try:
self.db.share_replica_delete(
context, share_replica['id'],
need_to_update_usages=False)
finally:
QUOTAS.rollback(
context, reservations, share_type_id=share_type['id'])
all_replicas = self.db.share_replicas_get_all_by_share(
context, share['id'])
all_hosts = [r['host'] for r in all_replicas]
request_spec['active_replica_host'] = active_replica['host']
request_spec['all_replica_hosts'] = ','.join(all_hosts)
self.db.share_replica_update(
context, share_replica['id'],
{'replica_state': constants.REPLICA_STATE_OUT_OF_SYNC})
existing_snapshots = (
self.db.share_snapshot_get_all_for_share(
context, share_replica['share_id'])
)
snapshot_instance = {
'status': constants.STATUS_CREATING,
'progress': '0%',
'share_instance_id': share_replica['id'],
}
for snapshot in existing_snapshots:
self.db.share_snapshot_instance_create(
context, snapshot['id'], snapshot_instance)
self.scheduler_rpcapi.create_share_replica(
context, request_spec=request_spec,
filter_properties={'scheduler_hints': scheduler_hints})
return share_replica
def delete_share_replica(self, context, share_replica, force=False):
# Disallow deletion of ONLY active replica, *even* when this
# operation is forced.
replicas = self.db.share_replicas_get_all_by_share(
context, share_replica['share_id'])
active_replicas = list(filter(
lambda x: x['replica_state'] == constants.REPLICA_STATE_ACTIVE,
replicas))
if (share_replica.get('replica_state') ==
constants.REPLICA_STATE_ACTIVE and len(active_replicas) == 1):
msg = _("Cannot delete last active replica.")
raise exception.ReplicationException(reason=msg)
LOG.info("Deleting replica %s.", share_replica['id'])
self.db.share_replica_update(
context, share_replica['id'],
{
'status': constants.STATUS_DELETING,
'terminated_at': timeutils.utcnow(),
}
)
if not share_replica['host']:
# Delete any snapshot instances created on the database
replica_snapshots = (
self.db.share_snapshot_instance_get_all_with_filters(
context, {'share_instance_ids': share_replica['id']})
)
for snapshot in replica_snapshots:
self.db.share_snapshot_instance_delete(context, snapshot['id'])
# Delete the replica from the database
self.db.share_replica_delete(context, share_replica['id'])
else:
self.share_rpcapi.delete_share_replica(context,
share_replica,
force=force)
def promote_share_replica(self, context, share_replica,
quiesce_wait_time=None):
if share_replica.get('status') != constants.STATUS_AVAILABLE:
msg = _("Replica %(replica_id)s must be in %(status)s state to be "
"promoted.")
raise exception.ReplicationException(
reason=msg % {'replica_id': share_replica['id'],
'status': constants.STATUS_AVAILABLE})
replica_state = share_replica['replica_state']
if (replica_state in (constants.REPLICA_STATE_OUT_OF_SYNC,
constants.STATUS_ERROR)
and not context.is_admin):
msg = _("Promoting a replica with 'replica_state': %s requires "
"administrator privileges.")
raise exception.AdminRequired(
message=msg % replica_state)
self.db.share_replica_update(
context, share_replica['id'],
{'status': constants.STATUS_REPLICATION_CHANGE})
self.share_rpcapi.promote_share_replica(
context, share_replica,
quiesce_wait_time=quiesce_wait_time)
return self.db.share_replica_get(context, share_replica['id'])
def update_share_replica(self, context, share_replica):
if not share_replica['host']:
msg = _("Share replica does not have a valid host.")
raise exception.InvalidHost(reason=msg)
self.share_rpcapi.update_share_replica(context, share_replica)
def manage(self, context, share_data, driver_options):
# Check whether there's a share already with the provided options:
filters = {
'export_location_path': share_data['export_location_path'],
'host': share_data['host'],
}
share_server_id = share_data.get('share_server_id')
if share_server_id:
filters['share_server_id'] = share_data['share_server_id']
already_managed = self.db.share_instance_get_all(
context, filters=filters)
if already_managed:
LOG.error("Found an existing share with export location %s!",
share_data['export_location_path'])
msg = _("A share already exists with the export path specified.")
raise exception.InvalidShare(reason=msg)
share_type_id = share_data['share_type_id']
share_type = share_types.get_share_type(context, share_type_id)
dhss = share_types.parse_boolean_extra_spec(
'driver_handles_share_servers',
share_type['extra_specs']['driver_handles_share_servers'])
if dhss and not share_server_id:
msg = _("Share Server ID parameter is required when managing a "
"share using a share type with "
"driver_handles_share_servers extra-spec set to True.")
raise exception.InvalidInput(reason=msg)
if not dhss and share_server_id:
msg = _("Share Server ID parameter is not expected when managing a"
" share using a share type with "
"driver_handles_share_servers extra-spec set to False.")
raise exception.InvalidInput(reason=msg)
if share_server_id:
try:
share_server = self.db.share_server_get(
context, share_data['share_server_id'])
except exception.ShareServerNotFound:
msg = _("Share Server specified was not found.")
raise exception.InvalidInput(reason=msg)
if share_server['status'] != constants.STATUS_ACTIVE:
msg = _("The provided share server is not active.")
raise exception.InvalidShareServer(reason=msg)
share_data['share_network_id'] = (
share_server['share_network_id'])
try:
share_network = self.db.share_network_get(
context, share_data['share_network_id'])
except exception.ShareNetworkNotFound:
msg = _("Share network %s was not found."
) % share_data['share_network_id']
raise exception.InvalidInput(reason=msg)