forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlinstorvolumemanager.py
More file actions
executable file
·3270 lines (2798 loc) · 116 KB
/
Copy pathlinstorvolumemanager.py
File metadata and controls
executable file
·3270 lines (2798 loc) · 116 KB
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
#!/usr/bin/env python3
#
# Copyright (C) 2020 Vates SAS - ronan.abhamon@vates.fr
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
from sm_typing import (
Any,
Dict,
List,
cast,
override,
)
import json
import linstor
import os.path
import re
import shutil
import socket
import stat
import time
import util
import uuid
# Persistent prefix to add to RAW persistent volumes.
PERSISTENT_PREFIX = 'xcp-persistent-'
# Contains the data of the "/var/lib/linstor" directory.
DATABASE_VOLUME_NAME = PERSISTENT_PREFIX + 'database'
DATABASE_SIZE = 1 << 30 # 1GB.
DATABASE_PATH = '/var/lib/linstor'
DATABASE_MKFS = 'mkfs.ext4'
LINSTOR_SATELLITE_PORT = 3366
REG_DRBDADM_PRIMARY = re.compile("([^\\s]+)\\s+role:Primary")
REG_DRBDSETUP_IP = re.compile('[^\\s]+\\s+(.*):.*$')
DRBD_BY_RES_PATH = '/dev/drbd/by-res/'
PLUGIN = 'linstor-manager'
LinstorLocalVolumeOpeners = Dict[str, Dict[str, Any]]
LinstorVolumeOpeners = Dict[str, LinstorLocalVolumeOpeners]
# ==============================================================================
def get_local_volume_openers(resource_name, volume) -> LinstorLocalVolumeOpeners:
if not resource_name or volume is None:
raise Exception('Cannot get DRBD openers without resource name and/or volume.')
path = '/sys/kernel/debug/drbd/resources/{}/volumes/{}/openers'.format(
resource_name, volume
)
with open(path, 'r') as openers:
# Not a big cost, so read all lines directly.
lines = openers.readlines()
result = {}
opener_re = re.compile('(.*)\\s+([0-9]+)\\s+([0-9]+)')
for line in lines:
match = opener_re.match(line)
assert match
groups = match.groups()
process_name = groups[0]
pid = groups[1]
open_duration_ms = groups[2]
try:
cmdline = util.get_process_cmdline(int(pid))
except Exception as e:
util.SMlog(f"Failed to get command line of `{pid}`: {e}")
cmdline = []
result[pid] = {
'process-name': process_name,
'open-duration': open_duration_ms,
'cmdline': cmdline
}
return cast(LinstorLocalVolumeOpeners, json.dumps(result))
def get_all_volume_openers(resource_name, volume) -> LinstorVolumeOpeners:
PLUGIN_CMD = 'getDrbdOpeners'
volume = str(volume)
openers = {}
with util.ApiSession("SM-get-linstor-volume-openers") as session:
hosts = session.xenapi.host.get_all_records()
for host_ref, host_record in hosts.items():
node_name = host_record['hostname']
try:
if not session.xenapi.host_metrics.get_record(
host_record['metrics']
)['live']:
# Ensure we call plugin on online hosts only.
continue
openers[node_name] = json.loads(
session.xenapi.host.call_plugin(host_ref, PLUGIN, PLUGIN_CMD, {
'resourceName': resource_name,
'volume': volume
})
)
except Exception as e:
util.SMlog('Failed to get openers of `{}` on `{}`: {}'.format(
resource_name, node_name, e
))
return openers
# ==============================================================================
def round_up(value, divisor):
assert divisor
divisor = int(divisor)
return ((int(value) + divisor - 1) // divisor) * divisor
def round_down(value, divisor):
assert divisor
value = int(value)
return value - (value % int(divisor))
# ==============================================================================
def _get_controller_addresses() -> List[str]:
try:
(ret, stdout, stderr) = util.doexec([
"/usr/sbin/ss", "-tnpH", "state", "established", f"( sport = :{LINSTOR_SATELLITE_PORT} )"
])
if ret == 0:
return [
line.split()[3].rsplit(":", 1)[0]
for line in stdout.splitlines()
]
util.SMlog(f"Unexpected code {ret}: {stderr}")
except Exception as e:
util.SMlog(f"Unable to get controller addresses: {e}")
return []
def _get_controller_uri() -> str:
# TODO: Check that an IP address from the current pool is returned.
addresses = _get_controller_addresses()
return "linstor://" + addresses[0] if addresses else ""
def get_controller_uri():
retries = 0
while True:
uri = _get_controller_uri()
if uri:
return uri
retries += 1
if retries >= 30:
break
time.sleep(1)
def get_controller_node_name():
PLUGIN_CMD = 'hasControllerRunning'
(ret, stdout, stderr) = util.doexec([
'drbdadm', 'status', DATABASE_VOLUME_NAME
])
if ret == 0:
if stdout.startswith('{} role:Primary'.format(DATABASE_VOLUME_NAME)):
return 'localhost'
res = REG_DRBDADM_PRIMARY.search(stdout)
if res:
return res.groups()[0]
session = util.timeout(5, util.ApiSession, "SM-get-linstor-controller-node-name").session
for host_ref, host_record in session.xenapi.host.get_all_records().items():
node_name = host_record['hostname']
try:
if not session.xenapi.host_metrics.get_record(
host_record['metrics']
)['live']:
continue
if util.strtobool(session.xenapi.host.call_plugin(
host_ref, PLUGIN, PLUGIN_CMD, {}
)):
return node_name
except Exception as e:
util.SMlog('Failed to call plugin to get controller on `{}`: {}'.format(
node_name, e
))
def demote_drbd_resource(node_name, resource_name):
PLUGIN_CMD = 'demoteDrbdResource'
session = util.timeout(5, util.ApiSession, "SM-demote-drbd-resource").session
for host_ref, host_record in session.xenapi.host.get_all_records().items():
if host_record['hostname'] != node_name:
continue
try:
session.xenapi.host.call_plugin(
host_ref, PLUGIN, PLUGIN_CMD, {'resource_name': resource_name}
)
except Exception as e:
util.SMlog('Failed to demote resource `{}` on `{}`: {}'.format(
resource_name, node_name, e
))
raise Exception(
'Can\'t demote resource `{}`, unable to find node `{}`'
.format(resource_name, node_name)
)
# ==============================================================================
class LinstorVolumeManagerError(Exception):
ERR_GENERIC = 0,
ERR_VOLUME_EXISTS = 1,
ERR_VOLUME_NOT_EXISTS = 2,
ERR_VOLUME_DESTROY = 3,
ERR_GROUP_NOT_EXISTS = 4,
ERR_VOLUME_IN_USE = 5
def __init__(self, message, code=ERR_GENERIC):
super(LinstorVolumeManagerError, self).__init__(message)
self._code = code
@property
def code(self):
return self._code
# ==============================================================================
# Note:
# If a storage pool is not accessible after a network change:
# linstor node interface modify <NODE> default --ip <IP>
class LinstorVolumeManager(object):
"""
API to manager LINSTOR volumes in XCP-ng.
A volume in this context is a physical part of the storage layer.
"""
__slots__ = (
'_linstor', '_uri', '_logger', '_redundancy',
'_base_group_name', '_group_name', '_ha_group_name',
'_volumes', '_storage_pools', '_storage_pools_time',
'_kv_cache', '_resource_cache', '_volume_info_cache',
'_kv_cache_dirty', '_resource_cache_dirty', '_volume_info_cache_dirty',
'_resources_info_cache',
)
DEV_ROOT_PATH = DRBD_BY_RES_PATH
# Default sector size.
BLOCK_SIZE = 512
# List of volume properties.
PROP_METADATA = 'metadata'
PROP_NOT_EXISTS = 'not-exists'
PROP_VOLUME_NAME = 'volume-name'
PROP_IS_READONLY_TIMESTAMP = 'readonly-timestamp'
# A volume can only be locked for a limited duration.
# The goal is to give enough time to slaves to execute some actions on
# a device before an UUID update or a coalesce for example.
# Expiration is expressed in seconds.
LOCKED_EXPIRATION_DELAY = 1 * 60
# Used when volume uuid is being updated.
PROP_UPDATING_UUID_SRC = 'updating-uuid-src'
# States of property PROP_NOT_EXISTS.
STATE_EXISTS = '0'
STATE_NOT_EXISTS = '1'
STATE_CREATING = '2'
# Property namespaces.
NAMESPACE_SR = 'xcp/sr'
NAMESPACE_VOLUME = 'xcp/volume'
# Regex to match properties.
REG_PROP = '^([^/]+)/{}$'
REG_METADATA = re.compile(REG_PROP.format(PROP_METADATA))
REG_NOT_EXISTS = re.compile(REG_PROP.format(PROP_NOT_EXISTS))
REG_VOLUME_NAME = re.compile(REG_PROP.format(PROP_VOLUME_NAME))
REG_UPDATING_UUID_SRC = re.compile(REG_PROP.format(PROP_UPDATING_UUID_SRC))
# Prefixes of SR/VOLUME in the LINSTOR DB.
# A LINSTOR (resource, group, ...) name cannot start with a number.
# So we add a prefix behind our SR/VOLUME uuids.
PREFIX_SR = 'xcp-sr-'
PREFIX_HA = 'xcp-ha-'
PREFIX_VOLUME = 'xcp-volume-'
# Limit request number when storage pool info is asked, we fetch
# the current pool status after N elapsed seconds.
STORAGE_POOLS_FETCH_INTERVAL = 15
@staticmethod
def default_logger(*args):
print(args)
# --------------------------------------------------------------------------
# API.
# --------------------------------------------------------------------------
class VolumeInfo(object):
__slots__ = (
'name',
'allocated_size', # Allocated size, place count is not used.
'virtual_size', # Total virtual available size of this volume
# (i.e. the user size at creation).
'diskful' # Array of nodes that have a diskful volume.
)
def __init__(self, name):
self.name = name
self.allocated_size = 0
self.virtual_size = 0
self.diskful = []
@override
def __repr__(self) -> str:
return 'VolumeInfo("{}", {}, {}, {})'.format(
self.name, self.allocated_size, self.virtual_size,
self.diskful
)
# --------------------------------------------------------------------------
def __init__(
self, uri, group_name, repair=False, logger=default_logger.__func__,
attempt_count=30
):
"""
Create a new LinstorVolumeManager object.
:param str uri: URI to communicate with the LINSTOR controller.
:param str group_name: The SR group name to use.
:param bool repair: If true we try to remove bad volumes due to a crash
or unexpected behavior.
:param function logger: Function to log messages.
:param int attempt_count: Number of attempts to join the controller.
"""
self._uri = uri
self._linstor = self._create_linstor_instance(
uri, attempt_count=attempt_count
)
mismatched_nodes = [
node for node in self._linstor.node_list().pop().nodes if node.connection_status == "VERSION_MISMATCH"
]
if mismatched_nodes:
raise LinstorVolumeManagerError(
"Some linstor nodes are not using the same version. " +
f"Incriminated nodes are: {','.join([node.name for node in mismatched_nodes])}"
)
self._base_group_name = group_name
# Ensure group exists.
group_name = self.build_group_name(group_name)
groups = self._linstor.resource_group_list_raise([group_name]).resource_groups
if not groups:
raise LinstorVolumeManagerError(
'Unable to find `{}` Linstor SR'.format(group_name)
)
# Ok. ;)
self._logger = logger
self._redundancy = groups[0].select_filter.place_count
self._group_name = group_name
self._ha_group_name = self._build_ha_group_name(self._base_group_name)
self._volumes = set()
self._storage_pools_time = 0
# To increase performance and limit request count to LINSTOR services,
# we use caches.
self._kv_cache = self._create_kv_cache()
self._resource_cache = None
self._resource_cache_dirty = True
self._volume_info_cache = None
self._volume_info_cache_dirty = True
self._resources_info_cache = None
self._build_volumes(repair=repair)
@property
def uri(self) -> str:
return self._uri
@property
def native_client(self) -> linstor.Linstor:
return self._linstor
@property
def group_name(self):
"""
Give the used group name.
:return: The group name.
:rtype: str
"""
return self._base_group_name
@property
def redundancy(self):
"""
Give the used redundancy.
:return: The redundancy.
:rtype: int
"""
return self._redundancy
@property
def volumes(self):
"""
Give the volumes uuid set.
:return: The volumes uuid set.
:rtype: set(str)
"""
return self._volumes
@property
def max_volume_size_allowed(self):
"""
Give the max volume size currently available in B.
:return: The current size.
:rtype: int
"""
candidates = self._find_best_size_candidates()
if not candidates:
raise LinstorVolumeManagerError(
'Failed to get max volume size allowed'
)
size = candidates[0].max_volume_size
if size < 0:
raise LinstorVolumeManagerError(
'Invalid max volume size allowed given: {}'.format(size)
)
return self.round_down_volume_size(size * 1024)
@property
def physical_size(self):
"""
Give the total physical size of the SR.
:return: The physical size.
:rtype: int
"""
return self._compute_size('total_capacity')
@property
def physical_free_size(self):
"""
Give the total free physical size of the SR.
:return: The physical free size.
:rtype: int
"""
return self._compute_size('free_capacity')
@property
def allocated_volume_size(self):
"""
Give the allocated size for all volumes. The place count is not
used here. When thick lvm is used, the size for one volume should
be equal to the virtual volume size. With thin lvm, the size is equal
or lower to the volume size.
:return: The allocated size of all volumes.
:rtype: int
"""
# Paths: /res_name/vol_number/size
sizes = {}
for resource in self._get_resource_cache().resources:
if resource.name not in sizes:
current = sizes[resource.name] = {}
else:
current = sizes[resource.name]
for volume in resource.volumes:
# We ignore diskless pools of the form "DfltDisklessStorPool".
if volume.storage_pool_name != self._group_name:
continue
allocated_size = max(volume.allocated_size, 0)
current_allocated_size = current.get(volume.number) or -1
if allocated_size > current_allocated_size:
current[volume.number] = allocated_size
total_size = 0
for volumes in sizes.values():
for size in volumes.values():
total_size += size
return total_size * 1024
def get_min_physical_size(self):
"""
Give the minimum physical size of the SR.
I.e. the size of the smallest disk + the number of pools.
:return: The physical min size.
:rtype: tuple(int, int)
"""
size = None
pool_count = 0
for pool in self._get_storage_pools(force=True):
space = pool.free_space
if space:
pool_count += 1
current_size = space.total_capacity
if current_size < 0:
raise LinstorVolumeManagerError(
'Failed to get pool total_capacity attr of `{}`'
.format(pool.node_name)
)
if size is None or current_size < size:
size = current_size
return (pool_count, (size or 0) * 1024)
@property
def metadata(self):
"""
Get the metadata of the SR.
:return: Dictionary that contains metadata.
:rtype: dict(str, dict)
"""
sr_properties = self._get_sr_properties()
metadata = sr_properties.get(self.PROP_METADATA)
if metadata is not None:
metadata = json.loads(metadata)
if isinstance(metadata, dict):
return metadata
raise LinstorVolumeManagerError(
'Expected dictionary in SR metadata: {}'.format(
self._group_name
)
)
return {}
@metadata.setter
def metadata(self, metadata):
"""
Set the metadata of the SR.
:param dict metadata: Dictionary that contains metadata.
"""
assert isinstance(metadata, dict)
sr_properties = self._get_sr_properties()
sr_properties[self.PROP_METADATA] = json.dumps(metadata)
@property
def disconnected_hosts(self):
"""
Get the list of disconnected hosts.
:return: Set that contains disconnected hosts.
:rtype: set(str)
"""
disconnected_hosts = set()
for pool in self._get_storage_pools():
for report in pool.reports:
if report.ret_code & linstor.consts.WARN_NOT_CONNECTED == \
linstor.consts.WARN_NOT_CONNECTED:
disconnected_hosts.add(pool.node_name)
break
return disconnected_hosts
def check_volume_exists(self, volume_uuid):
"""
Check if a volume exists in the SR.
:return: True if volume exists.
:rtype: bool
"""
return volume_uuid in self._volumes
def create_volume(
self,
volume_uuid,
size,
persistent=True,
volume_name=None,
high_availability=False
):
"""
Create a new volume on the SR.
:param str volume_uuid: The volume uuid to use.
:param int size: volume size in B.
:param bool persistent: If false the volume will be unavailable
on the next constructor call LinstorSR(...).
:param str volume_name: If set, this name is used in the LINSTOR
database instead of a generated name.
:param bool high_availability: If set, the volume is created in
the HA group.
:return: The current device path of the volume.
:rtype: str
"""
self._logger('Creating LINSTOR volume {}...'.format(volume_uuid))
if not volume_name:
volume_name = self.build_volume_name(util.gen_uuid())
volume_properties = self._create_volume_with_properties(
volume_uuid,
volume_name,
size,
True, # place_resources
high_availability
)
# Volume created! Now try to find the device path.
try:
self._logger(
'Find device path of LINSTOR volume {}...'.format(volume_uuid)
)
device_path = self._find_device_path(volume_uuid, volume_name)
if persistent:
volume_properties[self.PROP_NOT_EXISTS] = self.STATE_EXISTS
self._volumes.add(volume_uuid)
self._logger(
'LINSTOR volume {} created!'.format(volume_uuid)
)
return device_path
except Exception:
# There is an issue to find the path.
# At this point the volume has just been created, so force flag can be used.
self._destroy_volume(volume_uuid, force=True)
raise
def mark_volume_as_persistent(self, volume_uuid):
"""
Mark volume as persistent if created with persistent=False.
:param str volume_uuid: The volume uuid to mark.
"""
self._ensure_volume_exists(volume_uuid)
# Mark volume as persistent.
volume_properties = self._get_volume_properties(volume_uuid)
volume_properties[self.PROP_NOT_EXISTS] = self.STATE_EXISTS
def destroy_volume(self, volume_uuid):
"""
Destroy a volume.
:param str volume_uuid: The volume uuid to destroy.
"""
self._ensure_volume_exists(volume_uuid)
self.ensure_volume_is_not_locked(volume_uuid)
is_volume_in_use = any(node["in-use"] for node in self.get_resource_info(volume_uuid)["nodes"].values())
if is_volume_in_use:
raise LinstorVolumeManagerError(
f"Could not destroy volume `{volume_uuid}` as it is currently in use",
LinstorVolumeManagerError.ERR_VOLUME_IN_USE
)
# Mark volume as destroyed.
volume_properties = self._get_volume_properties(volume_uuid)
volume_properties[self.PROP_NOT_EXISTS] = self.STATE_NOT_EXISTS
try:
self._volumes.remove(volume_uuid)
self._destroy_volume(volume_uuid)
except Exception as e:
raise LinstorVolumeManagerError(
str(e),
LinstorVolumeManagerError.ERR_VOLUME_DESTROY
)
def lock_volume(self, volume_uuid, locked=True):
"""
Prevent modifications of the volume properties during
"self.LOCKED_EXPIRATION_DELAY" seconds. The SR must be locked
when used. This method is useful to attach/detach correctly a volume on
a slave. Without it the GC can rename a volume, in this case the old
volume path can be used by a slave...
:param str volume_uuid: The volume uuid to protect/unprotect.
:param bool locked: Lock/unlock the volume.
"""
self._ensure_volume_exists(volume_uuid)
self._logger(
'{} volume {} as locked'.format(
'Mark' if locked else 'Unmark',
volume_uuid
)
)
volume_properties = self._get_volume_properties(volume_uuid)
if locked:
volume_properties[
self.PROP_IS_READONLY_TIMESTAMP
] = str(time.time())
elif self.PROP_IS_READONLY_TIMESTAMP in volume_properties:
volume_properties.pop(self.PROP_IS_READONLY_TIMESTAMP)
def ensure_volume_is_not_locked(self, volume_uuid, timeout=None):
"""
Ensure a volume is not locked. Wait if necessary.
:param str volume_uuid: The volume uuid to check.
:param int timeout: If the volume is always locked after the expiration
of the timeout, an exception is thrown.
"""
return self.ensure_volume_list_is_not_locked([volume_uuid], timeout)
def ensure_volume_list_is_not_locked(self, volume_uuids, timeout=None):
checked = set()
for volume_uuid in volume_uuids:
if volume_uuid in self._volumes:
checked.add(volume_uuid)
if not checked:
return
waiting = False
volume_properties = self._get_kv_cache()
start = time.time()
while True:
# Can't delete in for loop, use a copy of the list.
remaining = checked.copy()
for volume_uuid in checked:
volume_properties.namespace = \
self._build_volume_namespace(volume_uuid)
timestamp = volume_properties.get(
self.PROP_IS_READONLY_TIMESTAMP
)
if timestamp is None:
remaining.remove(volume_uuid)
continue
now = time.time()
if now - float(timestamp) > self.LOCKED_EXPIRATION_DELAY:
self._logger(
'Remove readonly timestamp on {}'.format(volume_uuid)
)
volume_properties.pop(self.PROP_IS_READONLY_TIMESTAMP)
remaining.remove(volume_uuid)
continue
if not waiting:
self._logger(
'Volume {} is locked, waiting...'.format(volume_uuid)
)
waiting = True
break
if not remaining:
break
checked = remaining
if timeout is not None and now - start > timeout:
raise LinstorVolumeManagerError(
'volume `{}` is locked and timeout has been reached'
.format(volume_uuid),
LinstorVolumeManagerError.ERR_VOLUME_NOT_EXISTS
)
# We must wait to use the volume. After that we can modify it
# ONLY if the SR is locked to avoid bad reads on the slaves.
time.sleep(1)
volume_properties = self._create_kv_cache()
if waiting:
self._logger('No volume locked now!')
def remove_volume_if_diskless(self, volume_uuid):
"""
Remove disless path from local node.
:param str volume_uuid: The volume uuid to remove.
"""
self._ensure_volume_exists(volume_uuid)
volume_properties = self._get_volume_properties(volume_uuid)
volume_name = volume_properties.get(self.PROP_VOLUME_NAME)
node_name = socket.gethostname()
for resource in self._get_resource_cache().resources:
if resource.name == volume_name and resource.node_name == node_name:
if linstor.consts.FLAG_TIE_BREAKER in resource.flags:
return
break
result = self._linstor.resource_delete_if_diskless(
node_name=node_name, rsc_name=volume_name
)
if not linstor.Linstor.all_api_responses_no_error(result):
raise LinstorVolumeManagerError(
'Unable to delete diskless path of `{}` on node `{}`: {}'
.format(volume_name, node_name, ', '.join(
[str(x) for x in result]))
)
def introduce_volume(self, volume_uuid):
pass # TODO: Implement me.
def resize_volume(self, volume_uuid, new_size):
"""
Resize a volume.
:param str volume_uuid: The volume uuid to resize.
:param int new_size: New size in B.
"""
volume_name = self.get_volume_name(volume_uuid)
self.ensure_volume_is_not_locked(volume_uuid)
new_size = self.round_up_volume_size(new_size) // 1024
# We can't resize anything until DRBD is up to date.
# We wait here for 5min max and raise an easy to understand error for the user.
# 5min is an arbitrary time, it's impossible to get a fit all situation value
# and it's currently impossible to know how much time we have to wait
# This is mostly an issue for thick provisioning, thin isn't affected.
start_time = time.monotonic()
try:
self._linstor.resource_dfn_wait_synced(volume_name, wait_interval=1.0, timeout=60*5)
except linstor.LinstorTimeoutError:
raise LinstorVolumeManagerError(
f"Volume resizing of `{volume_uuid}` from SR `{self._group_name}` is incomplete: timeout reached but it continues in background."
)
util.SMlog(f"DRBD is up to date, syncing took {time.monotonic() - start_time}s")
result = self._linstor.volume_dfn_modify(
rsc_name=volume_name,
volume_nr=0,
size=new_size
)
self._mark_resource_cache_as_dirty()
error_str = self._get_error_str(result)
if error_str:
raise LinstorVolumeManagerError(
f"Could not resize volume `{volume_uuid}` from SR `{self._group_name}`: {error_str}"
)
def get_volume_name(self, volume_uuid):
"""
Get the name of a particular volume.
:param str volume_uuid: The volume uuid of the name to get.
:return: The volume name.
:rtype: str
"""
self._ensure_volume_exists(volume_uuid)
volume_properties = self._get_volume_properties(volume_uuid)
volume_name = volume_properties.get(self.PROP_VOLUME_NAME)
if volume_name:
return volume_name
raise LinstorVolumeManagerError(
'Failed to get volume name of {}'.format(volume_uuid)
)
def get_volume_size(self, volume_uuid):
"""
Get the size of a particular volume.
:param str volume_uuid: The volume uuid of the size to get.
:return: The volume size.
:rtype: int
"""
volume_name = self.get_volume_name(volume_uuid)
dfns = self._linstor.resource_dfn_list_raise(
query_volume_definitions=True,
filter_by_resource_definitions=[volume_name]
).resource_definitions
size = dfns[0].volume_definitions[0].size
if size < 0:
raise LinstorVolumeManagerError(
'Failed to get volume size of: {}'.format(volume_uuid)
)
return size * 1024
def set_auto_promote_timeout(self, volume_uuid, timeout):
"""
Define the blocking time of open calls when a DRBD
is already open on another host.
:param str volume_uuid: The volume uuid to modify.
"""
volume_name = self.get_volume_name(volume_uuid)
result = self._linstor.resource_dfn_modify(volume_name, {
'DrbdOptions/Resource/auto-promote-timeout': timeout
})
error_str = self._get_error_str(result)
if error_str:
raise LinstorVolumeManagerError(
'Could not change the auto promote timeout of `{}`: {}'
.format(volume_uuid, error_str)
)
def set_drbd_ha_properties(self, volume_name, enabled=True):
"""
Set or not HA DRBD properties required by drbd-reactor and
by specific volumes.
:param str volume_name: The volume to modify.
:param bool enabled: Enable or disable HA properties.
"""
properties = {
'DrbdOptions/auto-quorum': 'disabled',
'DrbdOptions/Resource/auto-promote': 'no',
'DrbdOptions/Resource/on-no-data-accessible': 'io-error',
'DrbdOptions/Resource/on-no-quorum': 'io-error',
'DrbdOptions/Resource/on-suspended-primary-outdated': 'force-secondary',
'DrbdOptions/Resource/quorum': 'majority'
}
if enabled:
result = self._linstor.resource_dfn_modify(volume_name, properties)
else:
result = self._linstor.resource_dfn_modify(volume_name, {}, delete_props=list(properties.keys()))
error_str = self._get_error_str(result)
if error_str:
raise LinstorVolumeManagerError(
'Could not modify HA DRBD properties on volume `{}`: {}'
.format(volume_name, error_str)
)
def get_volume_info(self, volume_uuid):
"""
Get the volume info of a particular volume.
:param str volume_uuid: The volume uuid of the volume info to get.
:return: The volume info.
:rtype: VolumeInfo
"""
volume_name = self.get_volume_name(volume_uuid)
return self._get_volumes_info()[volume_name]
def get_device_path(self, volume_uuid):
"""
Get the dev path of a volume, create a diskless if necessary.
:param str volume_uuid: The volume uuid to get the dev path.
:return: The current device path of the volume.
:rtype: str
"""
volume_name = self.get_volume_name(volume_uuid)
return self._find_device_path(volume_uuid, volume_name)
def get_volume_uuid_from_device_path(self, device_path):
"""
Get the volume uuid of a device_path.
:param str device_path: The dev path to find the volume uuid.
:return: The volume uuid of the local device path.
:rtype: str
"""
expected_volume_name = \
self.get_volume_name_from_device_path(device_path)
volume_names = self.get_volumes_with_name()
for volume_uuid, volume_name in volume_names.items():
if volume_name == expected_volume_name:
return volume_uuid
raise LinstorVolumeManagerError(
'Unable to find volume uuid from dev path `{}`'.format(device_path)
)
def get_volume_name_from_device_path(self, device_path):
"""
Get the volume name of a device_path.
:param str device_path: The dev path to find the volume name.
:return: The volume name of the device path.
:rtype: str