/
manager.py
6369 lines (5520 loc) · 284 KB
/
manager.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 (c) 2014 NetApp Inc.
# 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.
"""NAS share manager managers creating shares and access rights.
**Related Flags**
:share_driver: Used by :class:`ShareManager`.
"""
import copy
import datetime
import functools
import hashlib
import json
from operator import xor
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from oslo_service import periodic_task
from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import timeutils
from manila.common import constants
from manila import context
from manila import coordination
from manila.data import rpcapi as data_rpcapi
from manila import exception
from manila.i18n import _
from manila import manager
from manila.message import api as message_api
from manila.message import message_field
from manila import quota
from manila.share import access
from manila.share import api
from manila.share import configuration
from manila.share import drivers_private_data
from manila.share import migration
from manila.share import rpcapi as share_rpcapi
from manila.share import share_types
from manila.share import snapshot_access
from manila.share import utils as share_utils
from manila.transfer import api as transfer_api
from manila import utils
profiler = importutils.try_import('osprofiler.profiler')
LOG = log.getLogger(__name__)
share_manager_opts = [
cfg.StrOpt('share_driver',
default='manila.share.drivers.generic.GenericShareDriver',
help='Driver to use for share creation.'),
cfg.ListOpt('hook_drivers',
default=[],
help='Driver(s) to perform some additional actions before and '
'after share driver actions and on a periodic basis. '
'Default is [].'),
cfg.BoolOpt('delete_share_server_with_last_share',
default=False,
help='Whether share servers will '
'be deleted on deletion of the last share.'),
cfg.BoolOpt('unmanage_remove_access_rules',
default=False,
help='If set to True, then manila will deny access and remove '
'all access rules on share unmanage.'
'If set to False - nothing will be changed.'),
cfg.BoolOpt('automatic_share_server_cleanup',
default=True,
help='If set to True, then Manila will delete all share '
'servers which were unused more than specified time .'
'If set to False - automatic deletion of share servers '
'will be disabled.'),
cfg.IntOpt('unused_share_server_cleanup_interval',
default=10,
help='Unallocated share servers reclamation time interval '
'(minutes). Minimum value is 10 minutes, maximum is 60 '
'minutes. The reclamation function is run every '
'10 minutes and delete share servers which were unused '
'more than unused_share_server_cleanup_interval option '
'defines. This value reflects the shortest time Manila '
'will wait for a share server to go unutilized before '
'deleting it.',
min=10,
max=60),
cfg.IntOpt('replica_state_update_interval',
default=300,
help='This value, specified in seconds, determines how often '
'the share manager will poll for the health '
'(replica_state) of each replica instance.'),
cfg.IntOpt('migration_driver_continue_update_interval',
default=60,
help='This value, specified in seconds, determines how often '
'the share manager will poll the driver to perform the '
'next step of migration in the storage backend, for a '
'migrating share.'),
cfg.IntOpt('server_migration_driver_continue_update_interval',
default=900,
help='This value, specified in seconds, determines how often '
'the share manager will poll the driver to perform the '
'next step of migration in the storage backend, for a '
'migrating share server.'),
cfg.IntOpt('share_usage_size_update_interval',
default=300,
help='This value, specified in seconds, determines how often '
'the share manager will poll the driver to update the '
'share usage size in the storage backend, for shares in '
'that backend.'),
cfg.BoolOpt('enable_gathering_share_usage_size',
default=False,
help='If set to True, share usage size will be polled for in '
'the interval specified with '
'"share_usage_size_update_interval". Usage data can be '
'consumed by telemetry integration. If telemetry is not '
'configured, this option must be set to False. '
'If set to False - gathering share usage size will be'
' disabled.'),
cfg.BoolOpt('share_service_inithost_offload',
default=False,
help='Offload pending share ensure during '
'share service startup'),
cfg.IntOpt('check_for_expired_shares_in_recycle_bin_interval',
default=3600,
help='This value, specified in seconds, determines how often '
'the share manager will check for expired shares and '
'delete them from the Recycle bin.'),
cfg.IntOpt('check_for_expired_transfers',
default=300,
help='This value, specified in seconds, determines how often '
'the share manager will check for expired transfers and '
'destroy them and roll back share state.'),
]
CONF = cfg.CONF
CONF.register_opts(share_manager_opts)
CONF.import_opt('periodic_hooks_interval', 'manila.share.hook')
CONF.import_opt('periodic_interval', 'manila.service')
# Drivers that need to change module paths or class names can add their
# old/new path here to maintain backward compatibility.
MAPPING = {
'manila.share.drivers.netapp.cluster_mode.NetAppClusteredShareDriver':
'manila.share.drivers.netapp.common.NetAppDriver',
'manila.share.drivers.hp.hp_3par_driver.HP3ParShareDriver':
'manila.share.drivers.hpe.hpe_3par_driver.HPE3ParShareDriver',
'manila.share.drivers.hitachi.hds_hnas.HDSHNASDriver':
'manila.share.drivers.hitachi.hnas.driver.HitachiHNASDriver',
'manila.share.drivers.glusterfs_native.GlusterfsNativeShareDriver':
'manila.share.drivers.glusterfs.glusterfs_native.'
'GlusterfsNativeShareDriver',
'manila.share.drivers.emc.driver.EMCShareDriver':
'manila.share.drivers.dell_emc.driver.EMCShareDriver',
'manila.share.drivers.cephfs.cephfs_native.CephFSNativeDriver':
'manila.share.drivers.cephfs.driver.CephFSDriver',
}
QUOTAS = quota.QUOTAS
def locked_share_replica_operation(operation):
"""Lock decorator for share replica operations.
Takes a named lock prior to executing the operation. The lock is named with
the id of the share to which the replica belongs.
Intended use:
If a replica operation uses this decorator, it will block actions on
all share replicas of the share until the named lock is free. This is
used to protect concurrent operations on replicas of the same share e.g.
promote ReplicaA while deleting ReplicaB, both belonging to the same share.
"""
def wrapped(*args, **kwargs):
share_id = kwargs.get('share_id')
@coordination.synchronized(
'locked-share-replica-operation-for-share-%s' % share_id)
def locked_replica_operation(*_args, **_kwargs):
return operation(*_args, **_kwargs)
return locked_replica_operation(*args, **kwargs)
return wrapped
def locked_share_network_operation(operation):
"""Lock decorator for share network operations.
Takes a named lock prior to executing the operation. The lock is named with
the id of the share network.
"""
def wrapped(*args, **kwargs):
share_network_id = kwargs.get('share_network_id')
@coordination.synchronized(
'locked-share-network-operation-%s' % share_network_id)
def locked_network_operation(*_args, **_kwargs):
return operation(*_args, **_kwargs)
return locked_network_operation(*args, **kwargs)
return wrapped
def add_hooks(f):
"""Hook decorator to perform action before and after a share method call
The hook decorator can perform actions before some share driver methods
calls and after a call with results of driver call and preceding hook call.
"""
@functools.wraps(f)
def wrapped(self, *args, **kwargs):
if not self.hooks:
return f(self, *args, **kwargs)
pre_hook_results = []
for hook in self.hooks:
pre_hook_results.append(
hook.execute_pre_hook(
func_name=f.__name__,
*args, **kwargs))
wrapped_func_results = f(self, *args, **kwargs)
for i, hook in enumerate(self.hooks):
hook.execute_post_hook(
func_name=f.__name__,
driver_action_results=wrapped_func_results,
pre_hook_data=pre_hook_results[i],
*args, **kwargs)
return wrapped_func_results
return wrapped
class ShareManager(manager.SchedulerDependentManager):
"""Manages NAS storages."""
RPC_API_VERSION = '1.25'
def __init__(self, share_driver=None, service_name=None, *args, **kwargs):
"""Load the driver from args, or from flags."""
self.configuration = configuration.Configuration(
share_manager_opts,
config_group=service_name)
super(ShareManager, self).__init__(service_name='share',
*args, **kwargs)
if not share_driver:
share_driver = self.configuration.share_driver
if share_driver in MAPPING:
msg_args = {'old': share_driver, 'new': MAPPING[share_driver]}
LOG.warning("Driver path %(old)s is deprecated, update your "
"configuration to the new path %(new)s",
msg_args)
share_driver = MAPPING[share_driver]
ctxt = context.get_admin_context()
private_storage = drivers_private_data.DriverPrivateData(
context=ctxt, backend_host=self.host,
config_group=self.configuration.config_group
)
self.driver = importutils.import_object(
share_driver, private_storage=private_storage,
configuration=self.configuration,
)
backend_availability_zone = self.driver.configuration.safe_get(
'backend_availability_zone')
self.availability_zone = (
backend_availability_zone or CONF.storage_availability_zone
)
self.access_helper = access.ShareInstanceAccess(self.db, self.driver)
self.snapshot_access_helper = (
snapshot_access.ShareSnapshotInstanceAccess(self.db, self.driver))
self.migration_wait_access_rules_timeout = (
CONF.migration_wait_access_rules_timeout)
self.message_api = message_api.API()
self.share_api = api.API()
self.transfer_api = transfer_api.API()
if CONF.profiler.enabled and profiler is not None:
self.driver = profiler.trace_cls("driver")(self.driver)
self.hooks = []
self._init_hook_drivers()
self.service_id = None
def _init_hook_drivers(self):
# Try to initialize hook driver(s).
hook_drivers = self.configuration.safe_get("hook_drivers")
for hook_driver in hook_drivers:
self.hooks.append(
importutils.import_object(
hook_driver,
configuration=self.configuration,
host=self.host,
)
)
def _ensure_share_instance_has_pool(self, ctxt, share_instance):
pool = share_utils.extract_host(share_instance['host'], 'pool')
if pool is None:
# No pool name encoded in host, so this is a legacy
# share created before pool is introduced, ask
# driver to provide pool info if it has such
# knowledge and update the DB.
try:
pool = self.driver.get_pool(share_instance)
except Exception:
LOG.exception("Failed to fetch pool name for share: "
"%(share)s.",
{'share': share_instance['id']})
return
if pool:
new_host = share_utils.append_host(
share_instance['host'], pool)
self.db.share_instance_update(
ctxt, share_instance['id'], {'host': new_host})
return pool
@add_hooks
def init_host(self, service_id=None):
"""Initialization for a standalone service."""
self.service_id = service_id
ctxt = context.get_admin_context()
driver_host_pair = "{}@{}".format(
self.driver.__class__.__name__,
self.host)
# we want to retry to setup the driver. In case of a multi-backend
# scenario, working backends are usable and the non-working ones (where
# do_setup() or check_for_setup_error() fail) retry.
@utils.retry(interval=2, backoff_rate=2,
infinite=True, backoff_sleep_max=600)
def _driver_setup():
self.driver.initialized = False
LOG.debug("Start initialization of driver: '%s'", driver_host_pair)
try:
self.driver.do_setup(ctxt)
self.driver.check_for_setup_error()
except Exception:
LOG.exception("Error encountered during initialization of "
"driver %s", driver_host_pair)
raise
else:
self.driver.initialized = True
_driver_setup()
if (self.driver.driver_handles_share_servers and
hasattr(self.driver, 'service_instance_manager')):
(self.driver.service_instance_manager.network_helper.
setup_connectivity_with_service_instances())
self.ensure_driver_resources(ctxt)
self.publish_service_capabilities(ctxt)
LOG.info("Finished initialization of driver: '%(driver)s"
"@%(host)s'",
{"driver": self.driver.__class__.__name__,
"host": self.host})
def is_service_ready(self):
"""Return if Manager is ready to accept requests.
This is to inform Service class that in case of manila driver
initialization failure the manager is actually down and not ready to
accept any requests.
"""
return self.driver.initialized
def ensure_driver_resources(self, ctxt):
old_backend_info = self.db.backend_info_get(ctxt, self.host)
old_backend_info_hash = (old_backend_info.get('info_hash')
if old_backend_info is not None else None)
new_backend_info = None
new_backend_info_hash = None
backend_info_implemented = True
update_share_instances = []
try:
new_backend_info = self.driver.get_backend_info(ctxt)
except Exception as e:
if not isinstance(e, NotImplementedError):
LOG.exception(
"The backend %(host)s could not get backend info.",
{'host': self.host})
raise
else:
backend_info_implemented = False
LOG.debug(
("The backend %(host)s does not support get backend"
" info method."),
{'host': self.host})
if new_backend_info:
new_backend_info_hash = hashlib.sha1(str(
sorted(new_backend_info.items())).encode('utf-8')).hexdigest()
if (old_backend_info_hash == new_backend_info_hash and
backend_info_implemented):
LOG.debug(
("Ensure shares is being skipped because the %(host)s's old "
"backend info is the same as its new backend info."),
{'host': self.host})
return
share_instances = self.db.share_instances_get_all_by_host(
ctxt, self.host)
LOG.debug("Re-exporting %s shares", len(share_instances))
for share_instance in share_instances:
share_ref = self.db.share_get(ctxt, share_instance['share_id'])
if share_ref.is_busy:
LOG.info(
"Share instance %(id)s: skipping export, "
"because it is busy with an active task: %(task)s.",
{'id': share_instance['id'],
'task': share_ref['task_state']},
)
continue
if share_instance['status'] != constants.STATUS_AVAILABLE:
LOG.info(
"Share instance %(id)s: skipping export, "
"because it has '%(status)s' status.",
{'id': share_instance['id'],
'status': share_instance['status']},
)
continue
self._ensure_share_instance_has_pool(ctxt, share_instance)
share_instance = self.db.share_instance_get(
ctxt, share_instance['id'], with_share_data=True)
share_instance_dict = self._get_share_instance_dict(
ctxt, share_instance)
update_share_instances.append(share_instance_dict)
if update_share_instances:
try:
update_share_instances = self.driver.ensure_shares(
ctxt, update_share_instances) or {}
except Exception as e:
if not isinstance(e, NotImplementedError):
LOG.exception("Caught exception trying ensure "
"share instances.")
else:
for share_instance in update_share_instances:
if CONF.share_service_inithost_offload:
self._add_to_threadpool(self._ensure_share,
ctxt, share_instance)
else:
self._ensure_share(ctxt, share_instance)
if new_backend_info:
self.db.backend_info_update(
ctxt, self.host, new_backend_info_hash)
for share_instance in share_instances:
if share_instance['id'] not in update_share_instances:
continue
if update_share_instances[share_instance['id']].get('status'):
self.db.share_instance_update(
ctxt, share_instance['id'],
{'status': (
update_share_instances[share_instance['id']].
get('status')),
'host': share_instance['host']}
)
update_export_location = (
update_share_instances[share_instance['id']]
.get('export_locations'))
if update_export_location:
self.db.share_export_locations_update(
ctxt, share_instance['id'], update_export_location)
share_server = self._get_share_server(ctxt, share_instance)
if share_instance['access_rules_status'] != (
constants.STATUS_ACTIVE):
try:
# Cast any existing 'applying' rules to 'new'
self.access_helper.reset_applying_rules(
ctxt, share_instance['id'])
self.access_helper.update_access_rules(
ctxt, share_instance['id'], share_server=share_server)
except Exception:
LOG.exception(
("Unexpected error occurred while updating access "
"rules for share instance %(s_id)s."),
{'s_id': share_instance['id']},
)
snapshot_instances = (
self.db.share_snapshot_instance_get_all_with_filters(
ctxt, {'share_instance_ids': share_instance['id']},
with_share_data=True))
for snap_instance in snapshot_instances:
rules = (
self.db.
share_snapshot_access_get_all_for_snapshot_instance(
ctxt, snap_instance['id']))
# NOTE(ganso): We don't invoke update_access for snapshots if
# we don't have invalid rules or pending updates
if any(r['state'] in (constants.ACCESS_STATE_DENYING,
constants.ACCESS_STATE_QUEUED_TO_DENY,
constants.ACCESS_STATE_APPLYING,
constants.ACCESS_STATE_QUEUED_TO_APPLY)
for r in rules):
try:
self.snapshot_access_helper.update_access_rules(
ctxt, snap_instance['id'], share_server)
except Exception:
LOG.exception(
"Unexpected error occurred while updating "
"access rules for snapshot instance %s.",
snap_instance['id'])
def _ensure_share(self, ctxt, share_instance):
export_locations = None
try:
export_locations = self.driver.ensure_share(
ctxt, share_instance,
share_server=share_instance['share_server'])
except Exception:
LOG.exception("Caught exception trying ensure "
"share '%(s_id)s'.",
{'s_id': share_instance['id']})
if export_locations:
self.db.share_export_locations_update(
ctxt, share_instance['id'], export_locations)
def _check_share_server_backend_limits(
self, context, available_share_servers, share_instance=None):
max_shares_limit = self.driver.max_shares_per_share_server
max_server_size = self.driver.max_share_server_size
if max_server_size == max_shares_limit == -1:
return available_share_servers
for ss in available_share_servers[:]:
share_instances = self.db.share_instances_get_all_by_share_server(
context, ss['id'], with_share_data=True)
if not share_instances:
continue
share_instance_ids = [si['id'] for si in share_instances]
share_snapshot_instances = (
self.db.share_snapshot_instance_get_all_with_filters(
context, {"share_instance_ids": share_instance_ids},
with_share_data=True))
server_instances_size_sum = 0
num_instances = 0
server_instances_size_sum += sum(
instance['size'] for instance in share_instances)
server_instances_size_sum += sum(
instance['size'] for instance in share_snapshot_instances)
num_instances += len(share_instances)
# NOTE(carloss): If a share instance was not provided, means that
# a share group is being requested and there aren't shares to
# be added to to the sum yet.
if share_instance:
server_instances_size_sum += share_instance['size']
num_instances += 1
achieved_gigabytes_limit = (
max_server_size != -1 and (
server_instances_size_sum > max_server_size))
achieved_instances_limit = num_instances > max_shares_limit > -1
providing_server_for_share_migration = (
share_instance and share_instance['status'] ==
constants.STATUS_MIGRATING_TO)
src_server_id_equals_current_iteration = False
if providing_server_for_share_migration:
share = self.db.share_get(context, share_instance['share_id'])
src_instance_id, dest_instance_id = (
self.share_api.get_migrating_instances(share))
src_instance = self.db.share_instance_get(
context, src_instance_id)
src_server_id_equals_current_iteration = (
src_instance['share_server_id'] == ss['id'])
if (not src_server_id_equals_current_iteration and (
achieved_gigabytes_limit or achieved_instances_limit)):
available_share_servers.remove(ss)
return available_share_servers
def _provide_share_server_for_share(self, context, share_network_id,
share_instance, snapshot=None,
share_group=None,
create_on_backend=True):
"""Gets or creates share_server and updates share with its id.
Active share_server can be deleted if there are no dependent shares
on it.
So we need avoid possibility to delete share_server in time gap
between reaching active state for share_server and setting up
share_server_id for share. It is possible, for example, with first
share creation, which starts share_server creation.
For this purpose used shared lock between this method and the one
with deletion of share_server.
:param context: Current context
:param share_network_id: Share network where existing share server
should be found or created. If
share_network_id is None method use
share_network_id from provided snapshot.
:param share_instance: Share Instance model
:param snapshot: Optional -- Snapshot model
:param create_on_backend: Boolean. If True, driver will be asked to
create the share server if no share server
is available.
:returns: dict, dict -- first value is share_server, that
has been chosen for share schedule. Second value is
share updated with share_server_id.
"""
if not (share_network_id or snapshot):
msg = _("'share_network_id' parameter or 'snapshot'"
" should be provided. ")
raise ValueError(msg)
def error(msg, *args):
LOG.error(msg, *args)
self.db.share_instance_update(context, share_instance['id'],
{'status': constants.STATUS_ERROR})
parent_share_server = None
parent_share_same_dest = False
if snapshot:
parent_share_server_id = (
snapshot['share']['instance']['share_server_id'])
try:
parent_share_server = self.db.share_server_get(
context, parent_share_server_id)
except exception.ShareServerNotFound:
with excutils.save_and_reraise_exception():
error("Parent share server %s does not exist.",
parent_share_server_id)
if parent_share_server['status'] != constants.STATUS_ACTIVE:
error_params = {
'id': parent_share_server_id,
'status': parent_share_server['status'],
}
msg = _("Parent share server %(id)s has invalid status "
"'%(status)s'.")
error(msg, error_params)
raise exception.InvalidShareServer(reason=msg % error_params)
parent_share_same_dest = (snapshot['share']['instance']['host']
== share_instance['host'])
share_network_subnets = None
if share_network_id:
share_network_subnets = (
self.db.share_network_subnets_get_all_by_availability_zone_id(
context, share_network_id,
availability_zone_id=share_instance.get(
'availability_zone_id')))
if not share_network_subnets:
raise exception.ShareNetworkSubnetNotFound(
share_network_subnet_id=None)
elif parent_share_server:
share_network_subnets = (
parent_share_server['share_network_subnets'])
# NOTE(felipe_rodrigues): it can retrieve the available share
# servers using one single subnet_id from the availability zone
# subnets, because if the share server has one, it will have
# all subnets on that availability zone.
share_network_subnet_id = share_network_subnets[0]['id']
def get_available_share_servers():
if parent_share_server and parent_share_same_dest:
return [parent_share_server]
else:
return (
self.db
.share_server_get_all_by_host_and_share_subnet_valid(
context, self.host, share_network_subnet_id)
)
@utils.synchronized("share_manager_%s" % share_network_subnet_id,
external=True)
def _wrapped_provide_share_server_for_share():
try:
available_share_servers = get_available_share_servers()
except exception.ShareServerNotFound:
available_share_servers = None
# creating from snapshot in the same host must reuse the server,
# so it ignores the server limits.
if available_share_servers and not parent_share_same_dest:
available_share_servers = (
self._check_share_server_backend_limits(
context, available_share_servers,
share_instance=share_instance))
compatible_share_server = None
if available_share_servers:
try:
compatible_share_server = (
self.driver.choose_share_server_compatible_with_share(
context, available_share_servers, share_instance,
snapshot=snapshot.instance if snapshot else None,
share_group=share_group
)
)
except Exception as e:
with excutils.save_and_reraise_exception():
error("Cannot choose compatible share server: %s",
e)
if not compatible_share_server:
compatible_share_server = self.db.share_server_create(
context,
{
'host': self.host,
'share_network_subnets': share_network_subnets,
'status': constants.STATUS_CREATING,
'security_service_update_support': (
self.driver.security_service_update_support),
'network_allocation_update_support': (
self.driver.network_allocation_update_support),
}
)
msg = ("Using share_server %(share_server)s for share instance"
" %(share_instance_id)s")
LOG.debug(msg, {
'share_server': compatible_share_server['id'],
'share_instance_id': share_instance['id']
})
share_instance_ref = self.db.share_instance_update(
context,
share_instance['id'],
{'share_server_id': compatible_share_server['id']},
with_share_data=True
)
if create_on_backend:
metadata = self._build_server_metadata(
share_instance['host'], share_instance['share_type_id'])
compatible_share_server = (
self._create_share_server_in_backend(
context, compatible_share_server, metadata))
return compatible_share_server, share_instance_ref
return _wrapped_provide_share_server_for_share()
def _build_server_metadata(self, host, share_type_id):
return {
'request_host': host,
'share_type_id': share_type_id,
}
def _provide_share_server_for_migration(self, context,
source_share_server,
new_share_network_id,
availability_zone_id,
destination_host,
create_on_backend=True,
server_metadata=None):
"""Gets or creates share_server for a migration procedure.
Active share_server can be deleted if there are no dependent shares
on it.
So we need avoid possibility to delete share_server in time gap
between reaching active state for share_server and setting up
share_server_id for share. It is possible, for example, with first
share creation, which starts share_server creation.
For this purpose used shared lock between this method and the one
with deletion of share_server.
:param context: Current context
:param source_share_server: Share server model that will be migrated.
:param new_share_network_id: Share network where existing share server
should be found or created.
:param availability_zone_id: Id of the availability zone where the
new share server will be placed.
:param destination_host: The destination host where the new share
server will be created or retrieved.
:param create_on_backend: Boolean. If True, driver will be asked to
create the share server if no share server is available.
:param server_metadata: dict. Holds some important information that
can help drivers whether to create a new share server or not.
:returns: Share server that has been chosen for share server
migration.
"""
share_network_subnets = (
self.db.share_network_subnets_get_all_by_availability_zone_id(
context, new_share_network_id,
availability_zone_id=availability_zone_id))
if not share_network_subnets:
raise exception.ShareNetworkSubnetNotFound(
share_network_subnet_id=None)
server_metadata = {} if not server_metadata else server_metadata
@utils.synchronized(
"share_manager_%s" % share_network_subnets[0]['id'], external=True)
def _wrapped_provide_share_server_for_migration():
destination_share_server = self.db.share_server_create(
context,
{
'host': self.host,
'share_network_subnets': share_network_subnets,
'status': constants.STATUS_CREATING,
'security_service_update_support': (
self.driver.security_service_update_support),
'network_allocation_update_support': (
self.driver.network_allocation_update_support),
}
)
msg = ("Using share_server %(share_server)s as destination for "
"migration.")
LOG.debug(msg, {
'share_server': destination_share_server['id'],
})
if create_on_backend:
# NOTE(carloss): adding some information about the request, so
# backends that support share server migration and need to know
# if the request share server is from a share server migration
# request can use this metadata to take actions.
server_metadata['migration_destination'] = True
server_metadata['request_host'] = destination_host
server_metadata['source_share_server'] = (
source_share_server)
destination_share_server = (
self._create_share_server_in_backend(
context, destination_share_server,
metadata=server_metadata))
return destination_share_server
return _wrapped_provide_share_server_for_migration()
def _create_share_server_in_backend(self, context, share_server,
metadata):
"""Perform setup_server on backend
:param metadata: A dictionary, to be passed to driver's setup_server()
"""
if share_server['status'] == constants.STATUS_CREATING:
# Create share server on backend with data from db.
share_server = self._setup_server(context, share_server, metadata)
LOG.info("Share server created successfully.")
else:
LOG.info("Using preexisting share server: "
"'%(share_server_id)s'",
{'share_server_id': share_server['id']})
return share_server
def create_share_server(
self, context, share_server_id, share_instance_id):
"""Invoked to create a share server in this backend.
This method is invoked to create the share server defined in the model
obtained by the supplied id.
:param context: The 'context.RequestContext' object for the request.
:param share_server_id: The id of the server to be created.
:param share_instance_id: The id of the share instance
"""
share_server = self.db.share_server_get(context, share_server_id)
share = self.db.share_instance_get(
context, share_instance_id, with_share_data=True)
metadata = self._build_server_metadata(share['host'],
share['share_type_id'])
self._create_share_server_in_backend(context, share_server, metadata)
def provide_share_server(self, context, share_instance_id,
share_network_id, snapshot_id=None):
"""Invoked to provide a compatible share server.
This method is invoked to find a compatible share server among the
existing ones or create a share server database instance with the share
server properties that will be used to create the share server later.
:param context: The 'context.RequestContext' object for the request.
:param share_instance_id: The id of the share instance whose model
attributes will be used to provide the share server.
:param share_network_id: The id of the share network the share server
to be provided has to be related to.
:param snapshot_id: The id of the snapshot to be used to obtain the
share server if applicable.
:return: The id of the share server that is being provided.
"""
share_instance = self.db.share_instance_get(context, share_instance_id,
with_share_data=True)
snapshot_ref = None
if snapshot_id:
snapshot_ref = self.db.share_snapshot_get(context, snapshot_id)
share_group_ref = None
if share_instance.get('share_group_id'):
share_group_ref = self.db.share_group_get(
context, share_instance['share_group_id'])
share_server, share_instance = self._provide_share_server_for_share(
context, share_network_id, share_instance, snapshot_ref,
share_group_ref, create_on_backend=False)
return share_server['id']
def _provide_share_server_for_share_group(self, context,
share_network_id,
share_network_subnets,
share_group_ref,
share_group_snapshot=None):
"""Gets or creates share_server and updates share group with its id.
Active share_server can be deleted if there are no shares or share
groups dependent on it.
So we need avoid possibility to delete share_server in time gap
between reaching active state for share_server and setting up
share_server_id for share group. It is possible, for example, with
first share group creation, which starts share_server creation.
For this purpose used shared lock between this method and the one
with deletion of share_server.
:param context: Current context
:param share_network_id: Share network where existing share server
should be found or created.
:param share_network_subnets: Share network subnets where existing
share server should be found or created.
:param share_group_ref: Share Group model
:param share_group_snapshot: Optional -- ShareGroupSnapshot model. If
supplied, driver will use it to choose
the appropriate share server.
:returns: dict, dict -- first value is share_server, that
has been chosen for share group schedule.
Second value is share group updated with
share_server_id.
"""
if not share_network_id:
msg = _("'share_network_id' parameter should be provided. ")
raise exception.InvalidInput(reason=msg)
def error(msg, *args):
LOG.error(msg, *args)
self.db.share_group_update(
context, share_group_ref['id'],
{'status': constants.STATUS_ERROR})
@utils.synchronized("share_manager_%s" % share_network_id,
external=True)
def _wrapped_provide_share_server_for_share_group():
# NOTE(felipe_rodrigues): it can retrieve the available share
# servers using one single subnet_id from the availability zone
# subnets, because if the share server has one, it will have
# all subnets on that availability zone.
share_network_subnet_id = share_network_subnets[0]['id']
try:
available_share_servers = (
self.db
.share_server_get_all_by_host_and_share_subnet_valid(
context, self.host, share_network_subnet_id))
except exception.ShareServerNotFound:
available_share_servers = None
compatible_share_server = None
if available_share_servers:
available_share_servers = (
self._check_share_server_backend_limits(
context, available_share_servers))