/
rbd.py
2071 lines (1781 loc) · 89.4 KB
/
rbd.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 2013 OpenStack Foundation
#
# 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.
"""RADOS Block Device Driver"""
import binascii
import errno
import json
import math
import os
import tempfile
from castellan import key_manager
from eventlet import tpool
from os_brick.initiator import linuxrbd
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import loopingcall
from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import fileutils
from oslo_utils import units
try:
import rados
import rbd
except ImportError:
rados = None
rbd = None
import six
from six.moves import urllib
from cinder import exception
from cinder.i18n import _
from cinder.image import image_utils
from cinder import interface
from cinder import objects
from cinder.objects import fields
from cinder import utils
from cinder.volume import configuration
from cinder.volume import driver
from cinder.volume import volume_utils
LOG = logging.getLogger(__name__)
RBD_OPTS = [
cfg.StrOpt('rbd_cluster_name',
default='ceph',
help='The name of ceph cluster'),
cfg.StrOpt('rbd_pool',
default='rbd',
help='The RADOS pool where rbd volumes are stored'),
cfg.StrOpt('rbd_user',
help='The RADOS client name for accessing rbd volumes '
'- only set when using cephx authentication'),
cfg.StrOpt('rbd_ceph_conf',
default='', # default determined by librados
help='Path to the ceph configuration file'),
cfg.BoolOpt('rbd_flatten_volume_from_snapshot',
default=False,
help='Flatten volumes created from snapshots to remove '
'dependency from volume to snapshot'),
cfg.StrOpt('rbd_secret_uuid',
help='The libvirt uuid of the secret for the rbd_user '
'volumes'),
cfg.IntOpt('rbd_max_clone_depth',
default=5,
help='Maximum number of nested volume clones that are '
'taken before a flatten occurs. Set to 0 to disable '
'cloning. Note: lowering this value will not affect '
'existing volumes whose clone depth exceeds the new '
'value.'),
cfg.IntOpt('rbd_store_chunk_size', default=4,
help='Volumes will be chunked into objects of this size '
'(in megabytes).'),
cfg.IntOpt('rados_connect_timeout', default=-1,
help='Timeout value (in seconds) used when connecting to '
'ceph cluster. If value < 0, no timeout is set and '
'default librados value is used.'),
cfg.IntOpt('rados_connection_retries', default=3,
help='Number of retries if connection to ceph cluster '
'failed.'),
cfg.IntOpt('rados_connection_interval', default=5,
help='Interval value (in seconds) between connection '
'retries to ceph cluster.'),
cfg.IntOpt('replication_connect_timeout', default=5,
help='Timeout value (in seconds) used when connecting to '
'ceph cluster to do a demotion/promotion of volumes. '
'If value < 0, no timeout is set and default librados '
'value is used.'),
cfg.BoolOpt('report_dynamic_total_capacity', default=True,
help='Set to True for driver to report total capacity as a '
'dynamic value (used + current free) and to False to '
'report a static value (quota max bytes if defined and '
'global size of cluster if not).'),
cfg.BoolOpt('rbd_exclusive_cinder_pool', default=False,
help="Set to True if the pool is used exclusively by Cinder. "
"On exclusive use driver won't query images' provisioned "
"size as they will match the value calculated by the "
"Cinder core code for allocated_capacity_gb. This "
"reduces the load on the Ceph cluster as well as on the "
"volume service."),
cfg.BoolOpt('enable_deferred_deletion', default=False,
help='Enable deferred deletion. Upon deletion, volumes are '
'tagged for deletion but will only be removed '
'asynchronously at a later time.'),
cfg.IntOpt('deferred_deletion_delay', default=0,
help='Time delay in seconds before a volume is eligible '
'for permanent removal after being tagged for deferred '
'deletion.'),
cfg.IntOpt('deferred_deletion_purge_interval', default=60,
help='Number of seconds between runs of the periodic task '
'to purge volumes tagged for deletion.'),
]
CONF = cfg.CONF
CONF.register_opts(RBD_OPTS, group=configuration.SHARED_CONF_GROUP)
EXTRA_SPECS_REPL_ENABLED = "replication_enabled"
EXTRA_SPECS_MULTIATTACH = "multiattach"
# RBD
class RBDDriverException(exception.VolumeDriverException):
message = _("RBD Cinder driver failure: %(reason)s")
class RBDVolumeProxy(object):
"""Context manager for dealing with an existing rbd volume.
This handles connecting to rados and opening an ioctx automatically, and
otherwise acts like a librbd Image object.
Also this may reuse an external connection (client and ioctx args), but
note, that caller will be responsible for opening/closing connection.
Also `pool`, `remote`, `timeout` args will be ignored in that case.
The underlying librados client and ioctx can be accessed as the attributes
'client' and 'ioctx'.
"""
def __init__(self, driver, name, pool=None, snapshot=None,
read_only=False, remote=None, timeout=None,
client=None, ioctx=None):
self._close_conn = not (client and ioctx)
rados_client, rados_ioctx = driver._connect_to_rados(
pool, remote, timeout) if self._close_conn else (client, ioctx)
if snapshot is not None:
snapshot = utils.convert_str(snapshot)
try:
self.volume = driver.rbd.Image(rados_ioctx,
utils.convert_str(name),
snapshot=snapshot,
read_only=read_only)
self.volume = tpool.Proxy(self.volume)
except driver.rbd.Error:
if self._close_conn:
driver._disconnect_from_rados(rados_client, rados_ioctx)
raise
self.driver = driver
self.client = rados_client
self.ioctx = rados_ioctx
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
try:
self.volume.close()
finally:
if self._close_conn:
self.driver._disconnect_from_rados(self.client, self.ioctx)
def __getattr__(self, attrib):
return getattr(self.volume, attrib)
class RADOSClient(object):
"""Context manager to simplify error handling for connecting to ceph."""
def __init__(self, driver, pool=None):
self.driver = driver
self.cluster, self.ioctx = driver._connect_to_rados(pool)
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
self.driver._disconnect_from_rados(self.cluster, self.ioctx)
@property
def features(self):
features = self.cluster.conf_get('rbd_default_features')
if ((features is None) or (int(features) == 0)):
features = self.driver.RBD_FEATURE_LAYERING
return int(features)
@interface.volumedriver
class RBDDriver(driver.CloneableImageVD, driver.MigrateVD,
driver.ManageableVD, driver.ManageableSnapshotsVD,
driver.BaseVD):
"""Implements RADOS block device (RBD) volume commands."""
VERSION = '1.2.0'
# ThirdPartySystems wiki page
CI_WIKI_NAME = "Cinder_Jenkins"
SUPPORTS_ACTIVE_ACTIVE = True
SYSCONFDIR = '/etc/ceph/'
RBD_FEATURE_LAYERING = 1
RBD_FEATURE_EXCLUSIVE_LOCK = 4
RBD_FEATURE_OBJECT_MAP = 8
RBD_FEATURE_FAST_DIFF = 16
RBD_FEATURE_JOURNALING = 64
STORAGE_PROTOCOL = 'ceph'
def __init__(self, active_backend_id=None, *args, **kwargs):
super(RBDDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(RBD_OPTS)
self._stats = {}
# allow overrides for testing
self.rados = kwargs.get('rados', rados)
self.rbd = kwargs.get('rbd', rbd)
# All string args used with librbd must be None or utf-8 otherwise
# librbd will break.
for attr in ['rbd_cluster_name', 'rbd_user',
'rbd_ceph_conf', 'rbd_pool']:
val = getattr(self.configuration, attr)
if val is not None:
setattr(self.configuration, attr, utils.convert_str(val))
self._backend_name = (self.configuration.volume_backend_name or
self.__class__.__name__)
self._active_backend_id = active_backend_id
self._active_config = {}
self._is_replication_enabled = False
self._replication_targets = []
self._target_names = []
self._clone_v2_api_checked = False
if self.rbd is not None:
self.RBD_FEATURE_LAYERING = self.rbd.RBD_FEATURE_LAYERING
self.RBD_FEATURE_EXCLUSIVE_LOCK = \
self.rbd.RBD_FEATURE_EXCLUSIVE_LOCK
self.RBD_FEATURE_OBJECT_MAP = self.rbd.RBD_FEATURE_OBJECT_MAP
self.RBD_FEATURE_FAST_DIFF = self.rbd.RBD_FEATURE_FAST_DIFF
self.RBD_FEATURE_JOURNALING = self.rbd.RBD_FEATURE_JOURNALING
self.MULTIATTACH_EXCLUSIONS = (
self.RBD_FEATURE_JOURNALING |
self.RBD_FEATURE_FAST_DIFF |
self.RBD_FEATURE_OBJECT_MAP |
self.RBD_FEATURE_EXCLUSIVE_LOCK)
self._set_keyring_attributes()
def _set_keyring_attributes(self):
# The rbd_keyring_conf option is not available for OpenStack usage
# for security reasons (OSSN-0085) and in OpenStack we use
# rbd_secret_uuid or make sure that the keyring files are present on
# the hosts (where os-brick will look for them).
# For cinderlib usage this option is necessary (no security issue, as
# in those cases the contents of the connection are not available to
# users). By using getattr Oslo-conf won't read the option from the
# file even if it's there (because we have removed the conf option
# definition), but cinderlib will find it because it sets the option
# directly as an attribute.
self.keyring_file = getattr(self.configuration, 'rbd_keyring_conf',
None)
self.keyring_data = None
try:
if self.keyring_file and os.path.isfile(self.keyring_file):
with open(self.keyring_file, 'r') as k_file:
self.keyring_data = k_file.read()
except IOError:
LOG.debug('Cannot read RBD keyring file: %s.', self.keyring_file)
@classmethod
def get_driver_options(cls):
additional_opts = cls._get_oslo_driver_opts(
'replication_device', 'reserved_percentage',
'max_over_subscription_ratio', 'volume_dd_blocksize')
return RBD_OPTS + additional_opts
def _show_msg_check_clone_v2_api(self, volume_name):
if not self._clone_v2_api_checked:
self._clone_v2_api_checked = True
with RBDVolumeProxy(self, volume_name) as volume:
try:
if (volume.volume.op_features() &
self.rbd.RBD_OPERATION_FEATURE_CLONE_PARENT):
LOG.info('Using v2 Clone API')
return
except AttributeError:
pass
LOG.warning('Not using v2 clone API, please upgrade to'
' mimic+ and set the OSD minimum client'
' compat version to mimic for better'
' performance, fewer deletion issues')
def _get_target_config(self, target_id):
"""Get a replication target from known replication targets."""
for target in self._replication_targets:
if target['name'] == target_id:
return target
if not target_id or target_id == 'default':
return {
'name': self.configuration.rbd_cluster_name,
'conf': self.configuration.rbd_ceph_conf,
'user': self.configuration.rbd_user,
'secret_uuid': self.configuration.rbd_secret_uuid
}
raise exception.InvalidReplicationTarget(
reason=_('RBD: Unknown failover target host %s.') % target_id)
def do_setup(self, context):
"""Performs initialization steps that could raise exceptions."""
self._do_setup_replication()
self._active_config = self._get_target_config(self._active_backend_id)
def _do_setup_replication(self):
replication_devices = self.configuration.safe_get(
'replication_device')
if replication_devices:
self._parse_replication_configs(replication_devices)
self._is_replication_enabled = True
self._target_names.append('default')
def _parse_replication_configs(self, replication_devices):
for replication_device in replication_devices:
if 'backend_id' not in replication_device:
msg = _('Missing backend_id in replication_device '
'configuration.')
raise exception.InvalidConfigurationValue(msg)
name = replication_device['backend_id']
conf = replication_device.get('conf',
self.SYSCONFDIR + name + '.conf')
user = replication_device.get(
'user', self.configuration.rbd_user or 'cinder')
secret_uuid = replication_device.get(
'secret_uuid', self.configuration.rbd_secret_uuid)
# Pool has to be the same in all clusters
replication_target = {'name': name,
'conf': utils.convert_str(conf),
'user': utils.convert_str(user),
'secret_uuid': secret_uuid}
LOG.info('Adding replication target: %s.', name)
self._replication_targets.append(replication_target)
self._target_names.append(name)
def _get_config_tuple(self, remote=None):
if not remote:
remote = self._active_config
return (remote.get('name'), remote.get('conf'), remote.get('user'),
remote.get('secret_uuid', None))
def _trash_purge(self):
LOG.info("Purging trash for backend '%s'", self._backend_name)
with RADOSClient(self) as client:
for vol in self.RBDProxy().trash_list(client.ioctx):
try:
self.RBDProxy().trash_remove(client.ioctx, vol.get('id'))
LOG.info("Deleted %s from trash for backend '%s'",
vol.get('name'),
self._backend_name)
except Exception as e:
# NOTE(arne_wiebalck): trash_remove raises EPERM in case
# the volume's deferral time has not expired yet, so we
# want to explicitly handle this "normal" situation.
# All other exceptions, e.g. ImageBusy, are not re-raised
# so that the periodic purge retries on the next iteration
# and leaves ERRORs in the logs in case the deletion fails
# repeatedly.
if e.errno == errno.EPERM:
LOG.debug("%s has not expired yet on backend '%s'",
vol.get('name'),
self._backend_name)
else:
LOG.exception("Error deleting %s from trash "
"backend '%s'",
vol.get('name'),
self._backend_name)
def _start_periodic_tasks(self):
if self.configuration.enable_deferred_deletion:
LOG.info("Starting periodic trash purge for backend '%s'",
self._backend_name)
deferred_deletion_ptask = loopingcall.FixedIntervalLoopingCall(
self._trash_purge)
deferred_deletion_ptask.start(
interval=self.configuration.deferred_deletion_purge_interval)
def check_for_setup_error(self):
"""Returns an error if prerequisites aren't met."""
if rados is None:
msg = _('rados and rbd python libraries not found')
raise exception.VolumeBackendAPIException(data=msg)
for attr in ['rbd_cluster_name', 'rbd_pool']:
val = getattr(self.configuration, attr)
if not val:
raise exception.InvalidConfigurationValue(option=attr,
value=val)
# NOTE: Checking connection to ceph
# RADOSClient __init__ method invokes _connect_to_rados
# so no need to check for self.rados.Error here.
with RADOSClient(self):
pass
# NOTE(arne_wiebalck): If deferred deletion is enabled, check if the
# local Ceph client has support for the trash API.
if self.configuration.enable_deferred_deletion:
if not hasattr(self.RBDProxy(), 'trash_list'):
msg = _("Deferred deletion is enabled, but the local Ceph "
"client has no support for the trash API. Support "
"for this feature started with v12.2.0 Luminous.")
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
# If the keyring is defined (cinderlib usage), then the contents are
# necessary.
if self.keyring_file and not self.keyring_data:
msg = _('No keyring data found')
LOG.error(msg)
raise exception.InvalidConfigurationValue(
option='rbd_keyring_conf', value=self.keyring_file)
self._start_periodic_tasks()
def RBDProxy(self):
return tpool.Proxy(self.rbd.RBD())
def _ceph_args(self):
args = []
name, conf, user, secret_uuid = self._get_config_tuple()
if user:
args.extend(['--id', user])
if name:
args.extend(['--cluster', name])
if conf:
args.extend(['--conf', conf])
return args
def _connect_to_rados(self, pool=None, remote=None, timeout=None):
@utils.retry(exception.VolumeBackendAPIException,
self.configuration.rados_connection_interval,
self.configuration.rados_connection_retries)
def _do_conn(pool, remote, timeout):
name, conf, user, secret_uuid = self._get_config_tuple(remote)
if pool is not None:
pool = utils.convert_str(pool)
else:
pool = self.configuration.rbd_pool
if timeout is None:
timeout = self.configuration.rados_connect_timeout
LOG.debug("connecting to %(user)s@%(name)s (conf=%(conf)s, "
"timeout=%(timeout)s).",
{'user': user, 'name': name, 'conf': conf,
'timeout': timeout})
client = self.rados.Rados(rados_id=user,
clustername=name,
conffile=conf)
try:
if timeout >= 0:
timeout = six.text_type(timeout)
client.conf_set('rados_osd_op_timeout', timeout)
client.conf_set('rados_mon_op_timeout', timeout)
client.conf_set('client_mount_timeout', timeout)
client.connect()
ioctx = client.open_ioctx(pool)
return client, ioctx
except self.rados.Error:
msg = _("Error connecting to ceph cluster.")
LOG.exception(msg)
client.shutdown()
raise exception.VolumeBackendAPIException(data=msg)
return _do_conn(pool, remote, timeout)
def _disconnect_from_rados(self, client, ioctx):
# closing an ioctx cannot raise an exception
ioctx.close()
client.shutdown()
def _get_backup_snaps(self, rbd_image):
"""Get list of any backup snapshots that exist on this volume.
There should only ever be one but accept all since they need to be
deleted before the volume can be.
"""
# NOTE(dosaboy): we do the import here otherwise we get import conflict
# issues between the rbd driver and the ceph backup driver. These
# issues only seem to occur when NOT using them together and are
# triggered when the ceph backup driver imports the rbd volume driver.
from cinder.backup.drivers import ceph
return ceph.CephBackupDriver.get_backup_snaps(rbd_image)
def _get_mon_addrs(self):
args = ['ceph', 'mon', 'dump', '--format=json']
args.extend(self._ceph_args())
out, _ = self._execute(*args)
lines = out.split('\n')
if lines[0].startswith('dumped monmap epoch'):
lines = lines[1:]
monmap = json.loads('\n'.join(lines))
addrs = [mon['addr'] for mon in monmap['mons']]
hosts = []
ports = []
for addr in addrs:
host_port = addr[:addr.rindex('/')]
host, port = host_port.rsplit(':', 1)
hosts.append(host.strip('[]'))
ports.append(port)
return hosts, ports
def _get_usage_info(self):
"""Calculate provisioned volume space in GiB.
Stats report should send provisioned size of volumes (snapshot must not
be included) and not the physical size of those volumes.
We must include all volumes, not only Cinder created volumes, because
Cinder created volumes are reported by the Cinder core code as
allocated_capacity_gb.
"""
total_provisioned = 0
with RADOSClient(self) as client:
for t in self.RBDProxy().list(client.ioctx):
try:
with RBDVolumeProxy(self, t, read_only=True,
client=client.cluster,
ioctx=client.ioctx) as v:
size = v.size()
except (self.rbd.ImageNotFound, self.rbd.OSError):
LOG.debug("Image %s is not found.", t)
else:
total_provisioned += size
total_provisioned = math.ceil(float(total_provisioned) / units.Gi)
return total_provisioned
def _get_pool_stats(self):
"""Gets pool free and total capacity in GiB.
Calculate free and total capacity of the pool based on the pool's
defined quota and pools stats.
Returns a tuple with (free, total) where they are either unknown or a
real number with a 2 digit precision.
"""
pool_name = self.configuration.rbd_pool
with RADOSClient(self) as client:
ret, df_outbuf, __ = client.cluster.mon_command(
'{"prefix":"df", "format":"json"}', b'')
if ret:
LOG.warning('Unable to get rados pool stats.')
return 'unknown', 'unknown'
ret, quota_outbuf, __ = client.cluster.mon_command(
'{"prefix":"osd pool get-quota", "pool": "%s",'
' "format":"json"}' % pool_name, b'')
if ret:
LOG.warning('Unable to get rados pool quotas.')
return 'unknown', 'unknown'
df_outbuf = encodeutils.safe_decode(df_outbuf)
df_data = json.loads(df_outbuf)
pool_stats = [pool for pool in df_data['pools']
if pool['name'] == pool_name][0]['stats']
quota_outbuf = encodeutils.safe_decode(quota_outbuf)
bytes_quota = json.loads(quota_outbuf)['quota_max_bytes']
# With quota the total is the quota limit and free is quota - used
if bytes_quota:
total_capacity = bytes_quota
free_capacity = max(min(total_capacity - pool_stats['bytes_used'],
pool_stats['max_avail']),
0)
# Without quota free is pools max available and total is global size
else:
total_capacity = df_data['stats']['total_bytes']
free_capacity = pool_stats['max_avail']
# If we want dynamic total capacity (default behavior)
if self.configuration.safe_get('report_dynamic_total_capacity'):
total_capacity = free_capacity + pool_stats['bytes_used']
free_capacity = round((float(free_capacity) / units.Gi), 2)
total_capacity = round((float(total_capacity) / units.Gi), 2)
return free_capacity, total_capacity
def _update_volume_stats(self):
location_info = '%s:%s:%s:%s:%s' % (
self.configuration.rbd_cluster_name,
self.configuration.rbd_ceph_conf,
self._get_fsid(),
self.configuration.rbd_user,
self.configuration.rbd_pool)
stats = {
'vendor_name': 'Open Source',
'driver_version': self.VERSION,
'storage_protocol': self.STORAGE_PROTOCOL,
'total_capacity_gb': 'unknown',
'free_capacity_gb': 'unknown',
'reserved_percentage': (
self.configuration.safe_get('reserved_percentage')),
'multiattach': True,
'thin_provisioning_support': True,
'max_over_subscription_ratio': (
self.configuration.safe_get('max_over_subscription_ratio')),
'location_info': location_info,
'backend_state': 'down'
}
backend_name = self.configuration.safe_get('volume_backend_name')
stats['volume_backend_name'] = backend_name or 'RBD'
stats['replication_enabled'] = self._is_replication_enabled
if self._is_replication_enabled:
stats['replication_targets'] = self._target_names
try:
free_capacity, total_capacity = self._get_pool_stats()
stats['free_capacity_gb'] = free_capacity
stats['total_capacity_gb'] = total_capacity
# For exclusive pools let scheduler set provisioned_capacity_gb to
# allocated_capacity_gb, and for non exclusive query the value.
if not self.configuration.safe_get('rbd_exclusive_cinder_pool'):
total_gbi = self._get_usage_info()
stats['provisioned_capacity_gb'] = total_gbi
stats['backend_state'] = 'up'
except self.rados.Error:
# just log and return unknown capacities and let scheduler set
# provisioned_capacity_gb = allocated_capacity_gb
LOG.exception('error refreshing volume stats')
self._stats = stats
def _get_clone_depth(self, client, volume_name, depth=0):
"""Returns the number of ancestral clones of the given volume."""
parent_volume = self.rbd.Image(client.ioctx, volume_name)
try:
_pool, parent, _snap = self._get_clone_info(parent_volume,
volume_name)
finally:
parent_volume.close()
if not parent:
return depth
return self._get_clone_depth(client, parent, depth + 1)
def _extend_if_required(self, volume, src_vref):
"""Extends a volume if required
In case src_vref size is smaller than the size if the requested
new volume call _resize().
"""
if volume.size != src_vref.size:
LOG.debug("resize volume '%(dst_vol)s' from %(src_size)d to "
"%(dst_size)d",
{'dst_vol': volume.name, 'src_size': src_vref.size,
'dst_size': volume.size})
self._resize(volume)
def create_cloned_volume(self, volume, src_vref):
"""Create a cloned volume from another volume.
Since we are cloning from a volume and not a snapshot, we must first
create a snapshot of the source volume.
The user has the option to limit how long a volume's clone chain can be
by setting rbd_max_clone_depth. If a clone is made of another clone
and that clone has rbd_max_clone_depth clones behind it, the dest
volume will be flattened.
"""
src_name = utils.convert_str(src_vref.name)
dest_name = utils.convert_str(volume.name)
clone_snap = "%s.clone_snap" % dest_name
# Do full copy if requested
if self.configuration.rbd_max_clone_depth <= 0:
with RBDVolumeProxy(self, src_name, read_only=True) as vol:
vol.copy(vol.ioctx, dest_name)
self._extend_if_required(volume, src_vref)
return
# Otherwise do COW clone.
with RADOSClient(self) as client:
src_volume = self.rbd.Image(client.ioctx, src_name)
LOG.debug("creating snapshot='%s'", clone_snap)
try:
# Create new snapshot of source volume
src_volume.create_snap(clone_snap)
src_volume.protect_snap(clone_snap)
# Now clone source volume snapshot
LOG.debug("cloning '%(src_vol)s@%(src_snap)s' to "
"'%(dest)s'",
{'src_vol': src_name, 'src_snap': clone_snap,
'dest': dest_name})
self.RBDProxy().clone(client.ioctx, src_name, clone_snap,
client.ioctx, dest_name,
features=client.features)
except Exception as e:
src_volume.unprotect_snap(clone_snap)
src_volume.remove_snap(clone_snap)
src_volume.close()
msg = (_("Failed to clone '%(src_vol)s@%(src_snap)s' to "
"'%(dest)s', error: %(error)s") %
{'src_vol': src_name,
'src_snap': clone_snap,
'dest': dest_name,
'error': e})
LOG.exception(msg)
raise exception.VolumeBackendAPIException(data=msg)
depth = self._get_clone_depth(client, src_name)
# If dest volume is a clone and rbd_max_clone_depth reached,
# flatten the dest after cloning. Zero rbd_max_clone_depth means
# volumes are always flattened.
if depth >= self.configuration.rbd_max_clone_depth:
LOG.info("maximum clone depth (%d) has been reached - "
"flattening dest volume",
self.configuration.rbd_max_clone_depth)
# Flatten destination volume
try:
with RBDVolumeProxy(self, dest_name, client=client,
ioctx=client.ioctx) as dest_volume:
LOG.debug("flattening dest volume %s", dest_name)
dest_volume.flatten()
except Exception as e:
msg = (_("Failed to flatten volume %(volume)s with "
"error: %(error)s.") %
{'volume': dest_name,
'error': e})
LOG.exception(msg)
src_volume.close()
raise exception.VolumeBackendAPIException(data=msg)
try:
# remove temporary snap
LOG.debug("remove temporary snap %s", clone_snap)
src_volume.unprotect_snap(clone_snap)
src_volume.remove_snap(clone_snap)
except Exception as e:
msg = (_("Failed to remove temporary snap "
"%(snap_name)s, error: %(error)s") %
{'snap_name': clone_snap,
'error': e})
LOG.exception(msg)
src_volume.close()
raise exception.VolumeBackendAPIException(data=msg)
try:
volume_update = self._setup_volume(volume)
except Exception:
self.RBDProxy().remove(client.ioctx, dest_name)
src_volume.unprotect_snap(clone_snap)
src_volume.remove_snap(clone_snap)
err_msg = (_('Failed to enable image replication'))
raise exception.ReplicationError(reason=err_msg,
volume_id=volume.id)
finally:
src_volume.close()
self._extend_if_required(volume, src_vref)
LOG.debug("clone created successfully")
return volume_update
def _enable_replication(self, volume):
"""Enable replication for a volume.
Returns required volume update.
"""
vol_name = utils.convert_str(volume.name)
with RBDVolumeProxy(self, vol_name) as image:
had_exclusive_lock = (image.features() &
self.RBD_FEATURE_EXCLUSIVE_LOCK)
had_journaling = image.features() & self.RBD_FEATURE_JOURNALING
if not had_exclusive_lock:
image.update_features(self.RBD_FEATURE_EXCLUSIVE_LOCK,
True)
if not had_journaling:
image.update_features(self.RBD_FEATURE_JOURNALING, True)
image.mirror_image_enable()
driver_data = self._dumps({
'had_journaling': bool(had_journaling),
'had_exclusive_lock': bool(had_exclusive_lock)
})
return {'replication_status': fields.ReplicationStatus.ENABLED,
'replication_driver_data': driver_data}
def _enable_multiattach(self, volume):
vol_name = utils.convert_str(volume.name)
with RBDVolumeProxy(self, vol_name) as image:
image_features = image.features()
change_features = self.MULTIATTACH_EXCLUSIONS & image_features
image.update_features(change_features, False)
return {'provider_location':
self._dumps({'saved_features': image_features})}
def _disable_multiattach(self, volume):
vol_name = utils.convert_str(volume.name)
with RBDVolumeProxy(self, vol_name) as image:
try:
provider_location = json.loads(volume.provider_location)
image_features = provider_location['saved_features']
change_features = self.MULTIATTACH_EXCLUSIONS & image_features
image.update_features(change_features, True)
except IndexError:
msg = "Could not find saved image features."
raise RBDDriverException(reason=msg)
except self.rbd.InvalidArgument:
msg = "Failed to restore image features."
raise RBDDriverException(reason=msg)
return {'provider_location': None}
def _is_replicated_type(self, volume_type):
try:
extra_specs = volume_type.extra_specs
LOG.debug('extra_specs: %s', extra_specs)
return extra_specs.get(EXTRA_SPECS_REPL_ENABLED) == "<is> True"
except Exception:
LOG.debug('Unable to retrieve extra specs info')
return False
def _is_multiattach_type(self, volume_type):
try:
extra_specs = volume_type.extra_specs
LOG.debug('extra_specs: %s', extra_specs)
return extra_specs.get(EXTRA_SPECS_MULTIATTACH) == "<is> True"
except Exception:
LOG.debug('Unable to retrieve extra specs info')
return False
def _setup_volume(self, volume, volume_type=None):
if volume_type:
had_replication = self._is_replicated_type(volume.volume_type)
had_multiattach = self._is_multiattach_type(volume.volume_type)
else:
had_replication = False
had_multiattach = False
volume_type = volume.volume_type
want_replication = self._is_replicated_type(volume_type)
want_multiattach = self._is_multiattach_type(volume_type)
if want_replication and want_multiattach:
msg = _('Replication and Multiattach are mutually exclusive.')
raise RBDDriverException(reason=msg)
volume_update = dict()
if want_replication:
if had_multiattach:
volume_update.update(self._disable_multiattach(volume))
if not had_replication:
try:
volume_update.update(self._enable_replication(volume))
except Exception:
err_msg = (_('Failed to enable image replication'))
raise exception.ReplicationError(reason=err_msg,
volume_id=volume.id)
elif had_replication:
try:
volume_update.update(self._disable_replication(volume))
except Exception:
err_msg = (_('Failed to disable image replication'))
raise exception.ReplicationError(reason=err_msg,
volume_id=volume.id)
elif self._is_replication_enabled:
volume_update.update({'replication_status':
fields.ReplicationStatus.DISABLED})
if want_multiattach:
volume_update.update(self._enable_multiattach(volume))
elif had_multiattach:
volume_update.update(self._disable_multiattach(volume))
return volume_update
def _create_encrypted_volume(self, volume, context):
"""Create an encrypted volume.
This works by creating an encrypted image locally,
and then uploading it to the volume.
"""
encryption = volume_utils.check_encryption_provider(self.db,
volume,
context)
# Fetch the key associated with the volume and decode the passphrase
keymgr = key_manager.API(CONF)
key = keymgr.get(context, encryption['encryption_key_id'])
passphrase = binascii.hexlify(key.get_encoded()).decode('utf-8')
# create a file
tmp_dir = volume_utils.image_conversion_dir()
with tempfile.NamedTemporaryFile(dir=tmp_dir) as tmp_image:
with tempfile.NamedTemporaryFile(dir=tmp_dir) as tmp_key:
with open(tmp_key.name, 'w') as f:
f.write(passphrase)
cipher_spec = image_utils.decode_cipher(encryption['cipher'],
encryption['key_size'])
create_cmd = (
'qemu-img', 'create', '-f', 'luks',
'-o', 'cipher-alg=%(cipher_alg)s,'
'cipher-mode=%(cipher_mode)s,'
'ivgen-alg=%(ivgen_alg)s' % cipher_spec,
'--object', 'secret,id=luks_sec,'
'format=raw,file=%(passfile)s' % {'passfile':
tmp_key.name},
'-o', 'key-secret=luks_sec',
tmp_image.name,
'%sM' % (volume.size * 1024))
self._execute(*create_cmd)
# Copy image into RBD
chunk_size = self.configuration.rbd_store_chunk_size * units.Mi
order = int(math.log(chunk_size, 2))
cmd = ['rbd', 'import',
'--pool', self.configuration.rbd_pool,
'--order', order,
tmp_image.name, volume.name]
cmd.extend(self._ceph_args())
self._execute(*cmd)
def create_volume(self, volume):
"""Creates a logical volume."""
if volume.encryption_key_id:
return self._create_encrypted_volume(volume, volume.obj_context)
size = int(volume.size) * units.Gi
LOG.debug("creating volume '%s'", volume.name)
chunk_size = self.configuration.rbd_store_chunk_size * units.Mi
order = int(math.log(chunk_size, 2))
vol_name = utils.convert_str(volume.name)
with RADOSClient(self) as client:
self.RBDProxy().create(client.ioctx,
vol_name,
size,
order,
old_format=False,
features=client.features)
try:
volume_update = self._setup_volume(volume)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error('Error creating rbd image %(vol)s.',
{'vol': vol_name})
self.RBDProxy().remove(client.ioctx, vol_name)
return volume_update
def _flatten(self, pool, volume_name):
LOG.debug('flattening %(pool)s/%(img)s',