forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLinstorSR.py
More file actions
executable file
·2927 lines (2466 loc) · 107 KB
/
Copy pathLinstorSR.py
File metadata and controls
executable file
·2927 lines (2466 loc) · 107 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, Optional, override, Literal
from constants import CBTLOG_TAG, LINSTOR_AUTO_BACKUP_DELAY
try:
from linstorcowutil import LinstorCowUtil, MultiLinstorCowUtil
from linstorjournaler import LinstorJournaler
from linstorvolumemanager import get_controller_uri
from linstorvolumemanager import get_controller_node_name
from linstorvolumemanager import LinstorVolumeManager
from linstorvolumemanager import LinstorVolumeManagerError
from linstorvolumemanager import DATABASE_VOLUME_NAME
from linstorvolumemanager import PERSISTENT_PREFIX
LINSTOR_AVAILABLE = True
except ImportError:
PERSISTENT_PREFIX = 'unknown'
LINSTOR_AVAILABLE = False
import blktap2
import cleanup
import errno
import functools
import lock
import lvutil
import os
import re
import scsiutil
import signal
import socket
import SR
import SRCommand
import subprocess
import sys
import time
import traceback
import util
import VDI
import xml.etree.ElementTree as xml_parser
import xmlrpc.client
import xs_errors
from cowutil import CowUtil, ImageFormat, getImageStringFromVdiType
from srmetadata import \
NAME_LABEL_TAG, NAME_DESCRIPTION_TAG, IS_A_SNAPSHOT_TAG, SNAPSHOT_OF_TAG, \
TYPE_TAG, VDI_TYPE_TAG, READ_ONLY_TAG, SNAPSHOT_TIME_TAG, \
METADATA_OF_POOL_TAG
from vditype import VdiType
HIDDEN_TAG = 'hidden'
XHA_CONFIG_PATH = '/etc/xensource/xhad.conf'
FORK_LOG_DAEMON = '/opt/xensource/libexec/fork-log-daemon'
# This flag can be disabled to debug the DRBD layer.
# When this config var is False, the HA can only be used under
# specific conditions:
# - Only one heartbeat diskless VDI is present in the pool.
# - The other hearbeat volumes must be diskful and limited to a maximum of 3.
USE_HTTP_NBD_SERVERS = True
# Useful flag to trace calls using cProfile.
TRACE_PERFS = False
# Enable/Disable COW key hash support.
USE_KEY_HASH = False
# Special volumes.
HA_VOLUME_NAME = PERSISTENT_PREFIX + 'ha-statefile'
REDO_LOG_VOLUME_NAME = PERSISTENT_PREFIX + 'redo-log'
# ==============================================================================
# TODO: Supports 'VDI_INTRODUCE', 'VDI_RESET_ON_BOOT/2', 'SR_TRIM',
# 'VDI_CONFIG_CBT', 'SR_PROBE'
CAPABILITIES = [
'ATOMIC_PAUSE',
'SR_UPDATE',
'VDI_CREATE',
'VDI_DELETE',
'VDI_UPDATE',
'VDI_ATTACH',
'VDI_DETACH',
'VDI_ACTIVATE',
'VDI_DEACTIVATE',
'VDI_CLONE',
'VDI_MIRROR',
'VDI_RESIZE',
'VDI_SNAPSHOT',
'VDI_GENERATE_CONFIG'
]
CONFIGURATION = [
['group-name', 'LVM group name'],
['redundancy', 'replication count'],
['provisioning', '"thin" or "thick" are accepted (optional, defaults to thin)'],
['monitor-db-quorum', 'disable controller when only one host is online (optional, defaults to true)']
]
DRIVER_INFO = {
'name': 'LINSTOR resources on XCP-ng',
'description': 'SR plugin which uses Linstor to manage VDIs',
'vendor': 'Vates',
'copyright': '(C) 2020 Vates',
'driver_version': '1.0',
'required_api_version': '1.0',
'capabilities': CAPABILITIES,
'configuration': CONFIGURATION
}
DRIVER_CONFIG = {'ATTACH_FROM_CONFIG_WITH_TAPDISK': False}
OPS_EXCLUSIVE = [
'sr_create', 'sr_delete', 'sr_attach', 'sr_detach', 'sr_scan',
'sr_update', 'sr_probe', 'vdi_init', 'vdi_create', 'vdi_delete',
'vdi_attach', 'vdi_detach', 'vdi_clone', 'vdi_snapshot',
]
# ==============================================================================
# Misc helpers used by LinstorSR and linstor-thin plugin.
# ==============================================================================
def attach_thin(session, journaler, linstor, sr_uuid, vdi_uuid):
volume_metadata = linstor.get_volume_metadata(vdi_uuid)
vdi_type = volume_metadata.get(VDI_TYPE_TAG)
if not VdiType.isCowImage(vdi_type):
return
device_path = linstor.get_device_path(vdi_uuid)
linstorcowutil = LinstorCowUtil(session, linstor, vdi_type)
# If the virtual COW size is lower than the LINSTOR volume size,
# there is nothing to do.
cow_size = linstorcowutil.compute_volume_size(
linstorcowutil.get_size_virt(vdi_uuid)
)
volume_info = linstor.get_volume_info(vdi_uuid)
volume_size = volume_info.virtual_size
if cow_size > volume_size:
linstorcowutil.inflate(journaler, vdi_uuid, device_path, cow_size, volume_size)
def detach_thin_impl(session, linstor, sr_uuid, vdi_uuid):
volume_metadata = linstor.get_volume_metadata(vdi_uuid)
vdi_type = volume_metadata.get(VDI_TYPE_TAG)
if not VdiType.isCowImage(vdi_type):
return
def check_vbd_count():
vdi_ref = session.xenapi.VDI.get_by_uuid(vdi_uuid)
vbds = session.xenapi.VBD.get_all_records_where(
'field "VDI" = "{}"'.format(vdi_ref)
)
num_plugged = 0
for vbd_rec in vbds.values():
if vbd_rec['currently_attached']:
num_plugged += 1
if num_plugged > 1:
raise xs_errors.XenError(
'VDIUnavailable',
opterr='Cannot deflate VDI {}, already used by '
'at least 2 VBDs'.format(vdi_uuid)
)
# We can have multiple VBDs attached to a VDI during a VM-template clone.
# So we use a timeout to ensure that we can detach the volume properly.
util.retry(check_vbd_count, maxretry=10, period=1)
device_path = linstor.get_device_path(vdi_uuid)
linstorcowutil = LinstorCowUtil(session, linstor, vdi_type)
new_volume_size = LinstorVolumeManager.round_up_volume_size(
linstorcowutil.get_size_phys(vdi_uuid)
)
volume_info = linstor.get_volume_info(vdi_uuid)
old_volume_size = volume_info.virtual_size
linstorcowutil.deflate(device_path, new_volume_size, old_volume_size)
def detach_thin(session, linstor, sr_uuid, vdi_uuid):
# This function must always return without errors.
# Otherwise it could cause errors in the XAPI regarding the state of the VDI.
# It's why we use this `try` block.
try:
detach_thin_impl(session, linstor, sr_uuid, vdi_uuid)
except Exception as e:
util.SMlog('Failed to detach properly VDI {}: {}'.format(vdi_uuid, e))
def get_ips_from_xha_config_file():
ips = dict()
host_id = None
try:
# Ensure there is no dirty read problem.
# For example if the HA is reloaded.
tree = util.retry(
lambda: xml_parser.parse(XHA_CONFIG_PATH),
maxretry=10,
period=1
)
except:
return (None, ips)
def parse_host_nodes(ips, node):
current_id = None
current_ip = None
for sub_node in node:
if sub_node.tag == 'IPaddress':
current_ip = sub_node.text
elif sub_node.tag == 'HostID':
current_id = sub_node.text
else:
continue
if current_id and current_ip:
ips[current_id] = current_ip
return
util.SMlog('Ill-formed XHA file, missing IPaddress or/and HostID')
def parse_common_config(ips, node):
for sub_node in node:
if sub_node.tag == 'host':
parse_host_nodes(ips, sub_node)
def parse_local_config(ips, node):
for sub_node in node:
if sub_node.tag == 'localhost':
for host_node in sub_node:
if host_node.tag == 'HostID':
return host_node.text
for node in tree.getroot():
if node.tag == 'common-config':
parse_common_config(ips, node)
elif node.tag == 'local-config':
host_id = parse_local_config(ips, node)
else:
continue
if ips and host_id:
break
return (host_id and ips.get(host_id), ips)
def activate_lvm_group(group_name):
path = group_name.split('/')
assert path and len(path) <= 2
try:
lvutil.setActiveVG(path[0], True)
except Exception as e:
util.SMlog('Cannot active VG `{}`: {}'.format(path[0], e))
# ==============================================================================
# Usage example:
# xe sr-create type=linstor name-label=linstor-sr
# host-uuid=d2deba7a-c5ad-4de1-9a20-5c8df3343e93
# device-config:group-name=vg_loop device-config:redundancy=2
class LinstorSR(SR.SR):
DRIVER_TYPE = 'linstor'
PROVISIONING_TYPES = ['thin', 'thick']
PROVISIONING_DEFAULT = 'thin'
MANAGER_PLUGIN = 'linstor-manager'
INIT_STATUS_NOT_SET = 0
INIT_STATUS_IN_PROGRESS = 1
INIT_STATUS_OK = 2
INIT_STATUS_FAIL = 3
# --------------------------------------------------------------------------
# SR methods.
# --------------------------------------------------------------------------
_linstor: Optional["LinstorVolumeManager"] = None
@override
@staticmethod
def handles(type) -> bool:
return type == LinstorSR.DRIVER_TYPE
def __init__(self, srcmd, sr_uuid):
SR.SR.__init__(self, srcmd, sr_uuid)
self._init_image_formats(
preferred_image_formats=[ImageFormat.VHD],
supported_image_formats=[ImageFormat.RAW, ImageFormat.VHD]
)
@override
def load(self, sr_uuid) -> None:
if not LINSTOR_AVAILABLE:
raise util.SMException(
'Can\'t load LinstorSR: LINSTOR libraries are missing'
)
# Check parameters.
if 'group-name' not in self.dconf or not self.dconf['group-name']:
raise xs_errors.XenError('LinstorConfigGroupNameMissing')
if 'redundancy' not in self.dconf or not self.dconf['redundancy']:
raise xs_errors.XenError('LinstorConfigRedundancyMissing')
self.driver_config = DRIVER_CONFIG
# Check provisioning config.
provisioning = self.dconf.get('provisioning')
if provisioning:
if provisioning in self.PROVISIONING_TYPES:
self._provisioning = provisioning
else:
raise xs_errors.XenError(
'InvalidArg',
opterr='Provisioning parameter must be one of {}'.format(
self.PROVISIONING_TYPES
)
)
else:
self._provisioning = self.PROVISIONING_DEFAULT
monitor_db_quorum = self.dconf.get('monitor-db-quorum')
self._monitor_db_quorum = (monitor_db_quorum is None) or \
util.strtobool(monitor_db_quorum)
# Note: We don't have access to the session field if the
# 'vdi_attach_from_config' command is executed.
self._has_session = self.sr_ref and self.session is not None
if self._has_session:
self.sm_config = self.session.xenapi.SR.get_sm_config(self.sr_ref)
else:
self.sm_config = self.srcmd.params.get('sr_sm_config') or {}
provisioning = self.sm_config.get('provisioning')
if provisioning in self.PROVISIONING_TYPES:
self._provisioning = provisioning
# Define properties for SR parent class.
self.ops_exclusive = OPS_EXCLUSIVE
self.path = LinstorVolumeManager.DEV_ROOT_PATH
self.lock = lock.Lock(lock.LOCK_TYPE_SR, self.uuid)
self.sr_vditype = SR.DEFAULT_TAP
if self.cmd == 'sr_create':
self._redundancy = int(self.dconf['redundancy']) or 1
self._linstor = None # Ensure that LINSTOR attribute exists.
self._journaler = None
# Used to handle reconnect calls on LINSTOR object attached to the SR.
class LinstorProxy:
def __init__(self, sr: LinstorSR) -> None:
self.sr = sr
def __getattr__(self, attr: str) -> Any:
assert self.sr, "Cannot use `LinstorProxy` without valid `LinstorVolumeManager` instance"
return getattr(self.sr._linstor, attr)
self._linstor_proxy = LinstorProxy(self)
self._group_name = self.dconf['group-name']
self._vdi_shared_time = 0
self._init_status = self.INIT_STATUS_NOT_SET
self._vdis_loaded = False
self._all_volume_info_cache = None
self._all_volume_metadata_cache = None
self._multi_cowutil = None
# To remove in python 3.10.
# Use directly @staticmethod instead.
@util.conditional_decorator(staticmethod, sys.version_info >= (3, 10, 0))
def _locked_load(method):
def wrapped_method(self, *args, **kwargs):
self._init_status = self.INIT_STATUS_OK
return method(self, *args, **kwargs)
def load(self, *args, **kwargs):
# Activate all LVMs to make drbd-reactor happy.
if self.srcmd.cmd in ('sr_attach', 'vdi_attach_from_config'):
activate_lvm_group(self._group_name)
if not self._has_session:
if self.srcmd.cmd in (
'vdi_attach_from_config',
'vdi_detach_from_config',
# When on-slave (is_open) is executed we have an
# empty command.
None
):
def create_linstor(uri, attempt_count=30):
self._linstor = LinstorVolumeManager(
uri,
self._group_name,
logger=util.SMlog,
attempt_count=attempt_count
)
controller_uri = get_controller_uri()
if controller_uri:
create_linstor(controller_uri)
else:
def connect():
# We must have a valid LINSTOR instance here without using
# the XAPI. Fallback with the HA config file.
for ip in get_ips_from_xha_config_file()[1].values():
controller_uri = 'linstor://' + ip
try:
util.SMlog('Connecting from config to LINSTOR controller using: {}'.format(ip))
create_linstor(controller_uri, attempt_count=0)
return controller_uri
except:
pass
controller_uri = util.retry(connect, maxretry=30, period=1)
if not controller_uri:
raise xs_errors.XenError(
'SRUnavailable',
opterr='No valid controller URI to attach/detach from config'
)
return wrapped_method(self, *args, **kwargs)
if not self.is_master():
if self.cmd in [
'sr_create', 'sr_delete', 'sr_update', 'sr_probe',
'sr_scan', 'vdi_create', 'vdi_delete', 'vdi_resize',
'vdi_snapshot', 'vdi_clone'
]:
util.SMlog('{} blocked for non-master'.format(self.cmd))
raise xs_errors.XenError('LinstorMaster')
# Because the LINSTOR KV objects cache all values, we must lock
# the VDI before the LinstorJournaler/LinstorVolumeManager
# instantiation and before any action on the master to avoid a
# bad read. The lock is also necessary to avoid strange
# behaviors if the GC is executed during an action on a slave.
if self.cmd.startswith('vdi_'):
self._shared_lock_vdi(self.srcmd.params['vdi_uuid'])
self._vdi_shared_time = time.time()
if self.srcmd.cmd != 'sr_create' and self.srcmd.cmd != 'sr_detach':
try:
self._reconnect()
except Exception as e:
raise xs_errors.XenError('SRUnavailable', opterr=str(e))
if self._linstor:
try:
hosts = self._linstor.disconnected_hosts
except Exception as e:
raise xs_errors.XenError('SRUnavailable', opterr=str(e))
if hosts:
util.SMlog('Failed to join node(s): {}'.format(hosts))
# Ensure we use a non-locked volume when cowutil is called.
if (
self.is_master() and self.cmd.startswith('vdi_') and
self.cmd != 'vdi_create'
):
self._linstor.ensure_volume_is_not_locked(
self.srcmd.params['vdi_uuid']
)
try:
# If the command is a SR scan command on the master,
# we must load all VDIs and clean journal transactions.
# We must load the VDIs in the snapshot case too only if
# there is at least one entry in the journal.
#
# If the command is a SR command we want at least to remove
# resourceless volumes.
if self.is_master() and self.cmd not in [
'vdi_attach', 'vdi_detach',
'vdi_activate', 'vdi_deactivate',
'vdi_epoch_begin', 'vdi_epoch_end',
'vdi_update', 'vdi_destroy',
'nop' # Deal with `SR.from_uuid` that emits a fake `nop` command.
]:
journaler = self._get_journaler()
load_vdis = (
self.cmd == 'sr_scan' or
self.cmd == 'sr_attach'
) or len(
journaler.get_all(LinstorJournaler.INFLATE)
) or len(
journaler.get_all(LinstorJournaler.CLONE)
)
if load_vdis:
self._load_vdis()
self._linstor.remove_resourceless_volumes()
self._synchronize_metadata()
except Exception as e:
if self.cmd == 'sr_scan' or self.cmd == 'sr_attach':
# Always raise, we don't want to remove VDIs
# from the XAPI database otherwise.
raise e
util.SMlog(
'Ignoring exception in LinstorSR.load: {}'.format(e)
)
util.SMlog(traceback.format_exc())
return wrapped_method(self, *args, **kwargs)
@functools.wraps(wrapped_method)
def wrap(self, *args, **kwargs):
if self._init_status in \
(self.INIT_STATUS_OK, self.INIT_STATUS_IN_PROGRESS):
return wrapped_method(self, *args, **kwargs)
if self._init_status == self.INIT_STATUS_FAIL:
util.SMlog(
'Can\'t call method {} because initialization failed'
.format(method)
)
else:
try:
self._init_status = self.INIT_STATUS_IN_PROGRESS
return load(self, *args, **kwargs)
except Exception:
if self._init_status != self.INIT_STATUS_OK:
self._init_status = self.INIT_STATUS_FAIL
raise
return wrap
@override
def cleanup(self) -> None:
if self._vdi_shared_time:
self._shared_lock_vdi(self.srcmd.params['vdi_uuid'], locked=False)
@override
@_locked_load
def create(self, uuid, size) -> None:
util.SMlog('LinstorSR.create for {}'.format(self.uuid))
host_adresses = util.get_host_addresses(self.session)
if self._redundancy > len(host_adresses):
raise xs_errors.XenError(
'LinstorSRCreate',
opterr='Redundancy greater than host count'
)
srs = util.get_linstor_srs_uuid(self.session)
try:
srs.pop(self.uuid)
except KeyError:
# We cannot guarantee that the new SR key will be there even it should be the case.
pass
pbd_ref = util.find_pbd_ref_from_dconf_value(
self.session, srs, "group-name", self._group_name, LinstorVolumeManager.build_group_name
)
if pbd_ref:
raise xs_errors.XenError(
'LinstorSRCreate',
opterr=f"group name must be unique, already used by PBD {self.session.xenapi.PBD.get_uuid(pbd_ref)}"
)
if srs:
raise xs_errors.XenError(
'LinstorSRCreate',
opterr='LINSTOR SR must be unique in a pool'
)
online_hosts = util.get_enabled_hosts(self.session)
if len(online_hosts) < len(host_adresses):
raise xs_errors.XenError(
'LinstorSRCreate',
opterr='Not enough online hosts'
)
ips = {}
for host_ref in online_hosts:
record = self.session.xenapi.host.get_record(host_ref)
hostname = record['hostname']
ips[hostname] = record['address']
if len(ips) != len(online_hosts):
raise xs_errors.XenError(
'LinstorSRCreate',
opterr='Multiple hosts with same hostname'
)
# Ensure ports are opened and LINSTOR satellites
# are activated. In the same time the drbd-reactor instances
# must be stopped.
self._prepare_sr_on_all_hosts(self._group_name, enabled=True)
# Create SR.
# Throw if the SR already exists.
try:
self._linstor = LinstorVolumeManager.create_sr(
self._group_name,
ips,
self._redundancy,
thin_provisioning=self._provisioning == 'thin',
logger=util.SMlog
)
util.SMlog(
"Finishing SR creation, enable drbd-reactor on all hosts..."
)
self._update_drbd_reactor_on_all_hosts(enabled=True)
except Exception as e:
if not self._linstor:
util.SMlog('Failed to create LINSTOR SR: {}'.format(e))
raise xs_errors.XenError('LinstorSRCreate', opterr=str(e))
try:
self._linstor.destroy()
except Exception as e2:
util.SMlog(
'Failed to destroy LINSTOR SR after creation fail: {}'
.format(e2)
)
raise e
@override
@_locked_load
def delete(self, uuid) -> None:
util.SMlog('LinstorSR.delete for {}'.format(self.uuid))
cleanup.gc_force(self.session, self.uuid)
assert self._linstor
if self.vdis or self._linstor._volumes:
raise xs_errors.XenError('SRNotEmpty')
node_name = get_controller_node_name()
if not node_name:
raise xs_errors.XenError(
'LinstorSRDelete',
opterr='Cannot get controller node name'
)
host_ref = None
if node_name == 'localhost':
host_ref = util.get_this_host_ref(self.session)
else:
for slave in util.get_all_slaves(self.session):
r_name = self.session.xenapi.host.get_record(slave)['hostname']
if r_name == node_name:
host_ref = slave
break
if not host_ref:
raise xs_errors.XenError(
'LinstorSRDelete',
opterr='Failed to find host with hostname: {}'.format(
node_name
)
)
try:
if self._monitor_db_quorum:
self._linstor.set_drbd_ha_properties(DATABASE_VOLUME_NAME, enabled=False)
self._update_drbd_reactor_on_all_hosts(
controller_node_name=node_name, enabled=False
)
args = {
'groupName': self._group_name,
}
self._exec_manager_command(
host_ref, 'destroy', args, 'LinstorSRDelete'
)
except Exception as e:
try:
self._update_drbd_reactor_on_all_hosts(
controller_node_name=node_name, enabled=True
)
if self._monitor_db_quorum:
self._linstor.set_drbd_ha_properties(DATABASE_VOLUME_NAME, enabled=True)
except Exception as e2:
util.SMlog(
'Failed to restart drbd-reactor after destroy fail: {}'
.format(e2)
)
util.SMlog('Failed to delete LINSTOR SR: {}'.format(e))
raise xs_errors.XenError(
'LinstorSRDelete',
opterr=str(e)
)
lock.Lock.cleanupAll(self.uuid)
@override
@_locked_load
def update(self, uuid) -> None:
util.SMlog('LinstorSR.update for {}'.format(self.uuid))
# Well, how can we update a SR if it doesn't exist? :thinking:
if not self._linstor:
raise xs_errors.XenError(
'SRUnavailable',
opterr='no such volume group: {}'.format(self._group_name)
)
self._update_stats(0)
# Update the SR name and description only in LINSTOR metadata.
xenapi = self.session.xenapi
self._linstor.metadata = {
NAME_LABEL_TAG: util.to_plain_string(
xenapi.SR.get_name_label(self.sr_ref)
),
NAME_DESCRIPTION_TAG: util.to_plain_string(
xenapi.SR.get_name_description(self.sr_ref)
)
}
@override
@_locked_load
def attach(self, uuid) -> None:
util.SMlog('LinstorSR.attach for {}'.format(self.uuid))
if not self._linstor:
raise xs_errors.XenError(
'SRUnavailable',
opterr='no such group: {}'.format(self._group_name)
)
if self._monitor_db_quorum and self.is_master():
self._linstor.set_drbd_ha_properties(DATABASE_VOLUME_NAME)
@override
@_locked_load
def detach(self, uuid) -> None:
util.SMlog('LinstorSR.detach for {}'.format(self.uuid))
cleanup.abort(self.uuid)
@override
@_locked_load
def probe(self) -> str:
util.SMlog('LinstorSR.probe for {}'.format(self.uuid))
# TODO
return ''
@override
@_locked_load
def scan(self, uuid) -> None:
if self._init_status == self.INIT_STATUS_FAIL:
return
util.SMlog('LinstorSR.scan for {}'.format(self.uuid))
if not self._linstor:
raise xs_errors.XenError(
'SRUnavailable',
opterr='no such volume group: {}'.format(self._group_name)
)
# Note: `scan` can be called outside this module, so ensure the VDIs
# are loaded.
self._load_vdis()
self._update_physical_size()
for vdi_uuid in list(self.vdis.keys()):
if self.vdis[vdi_uuid].deleted:
del self.vdis[vdi_uuid]
# Security to prevent VDIs from being forgotten if the controller
# is started without a shared and mounted /var/lib/linstor path.
try:
self._linstor.get_database_path()
except Exception as e:
# Failed to get database path, ensure we don't have
# VDIs in the XAPI database...
if self.session.xenapi.SR.get_VDIs(
self.session.xenapi.SR.get_by_uuid(self.uuid)
):
raise xs_errors.XenError(
'SRUnavailable',
opterr='Database is not mounted or node name is invalid ({})'.format(e)
)
# Update the database before the restart of the GC to avoid
# bad sync in the process if new VDIs have been introduced.
super(LinstorSR, self).scan(self.uuid)
self._kick_gc()
def is_master(self):
if not hasattr(self, '_is_master'):
if 'SRmaster' not in self.dconf:
self._is_master = self.session is not None and util.is_master(self.session)
else:
self._is_master = self.dconf['SRmaster'] == 'true'
return self._is_master
@override
def check_sr(self, sr_uuid) -> None:
# Note: check_sr is called on all hosts by the health check mechanism
# not by regular xapi calls such as scans.
# Applied only on the Linstor Controller, for reasons -> listed below.
if not LinstorVolumeManager.is_controller():
return
# Validate and clean previous backups if necessary.
# -> Needs access to backup files, available only on the Controller.
LinstorVolumeManager.database_invalidation()
# check_sr is launched on *all* hosts, but it turns out that
# we do not want all of them to blindly generate concurrencing backups.
# Hence we must choose one, either one is good, but there must be only one.
# Apply throttling: only backup if last one is >1h old.
# -> Needs access to backup files, available only on the Controller.
if LinstorVolumeManager.get_database_backup_age() > LINSTOR_AUTO_BACKUP_DELAY:
self.database_backup("auto")
@override
@_locked_load
def vdi(self, uuid) -> VDI.VDI:
return LinstorVDI(self, uuid)
# To remove in python 3.10
# See: https://stackoverflow.com/questions/12718187/python-version-3-9-calling-class-staticmethod-within-the-class-body
_locked_load = staticmethod(_locked_load)
# --------------------------------------------------------------------------
# Lock.
# --------------------------------------------------------------------------
def _shared_lock_vdi(self, vdi_uuid, locked=True):
master = util.get_master_ref(self.session)
command = 'lockVdi'
args = {
'groupName': self._group_name,
'srUuid': self.uuid,
'vdiUuid': vdi_uuid,
'locked': str(locked)
}
# Note: We must avoid to unlock the volume if the timeout is reached
# because during volume unlock, the SR lock is not used. Otherwise
# we could destroy a valid lock acquired from another host...
#
# This code is not very clean, the ideal solution would be to acquire
# the SR lock during volume unlock (like lock) but it's not easy
# to implement without impacting performance.
if not locked:
elapsed_time = time.time() - self._vdi_shared_time
timeout = LinstorVolumeManager.LOCKED_EXPIRATION_DELAY * 0.7
if elapsed_time >= timeout:
util.SMlog(
'Avoid unlock call of {} because timeout has been reached'
.format(vdi_uuid)
)
return
self._exec_manager_command(master, command, args, 'VDIUnavailable')
# --------------------------------------------------------------------------
# Network.
# --------------------------------------------------------------------------
def _exec_manager_command(self, host_ref, command, args, error):
host_rec = self.session.xenapi.host.get_record(host_ref)
host_uuid = host_rec['uuid']
try:
ret = self.session.xenapi.host.call_plugin(
host_ref, self.MANAGER_PLUGIN, command, args
)
except Exception as e:
util.SMlog(
'call-plugin on {} ({}:{} with {}) raised'.format(
host_uuid, self.MANAGER_PLUGIN, command, args
)
)
raise e
util.SMlog(
'call-plugin on {} ({}:{} with {}) returned: {}'.format(
host_uuid, self.MANAGER_PLUGIN, command, args, ret
)
)
if ret == 'False':
raise xs_errors.XenError(
error,
opterr='Plugin {} failed'.format(self.MANAGER_PLUGIN)
)
def _prepare_sr(self, host, group_name, enabled):
self._exec_manager_command(
host,
'prepareSr' if enabled else 'releaseSr',
{'groupName': group_name},
'SRUnavailable'
)
def _prepare_sr_on_all_hosts(self, group_name, enabled):
master = util.get_master_ref(self.session)
self._prepare_sr(master, group_name, enabled)
for slave in util.get_all_slaves(self.session):
self._prepare_sr(slave, group_name, enabled)
def _update_drbd_reactor(self, host, enabled):
self._exec_manager_command(
host,
'updateDrbdReactor',
{'enabled': str(enabled)},
'SRUnavailable'
)
def _update_drbd_reactor_on_all_hosts(
self, enabled, controller_node_name=None
):
if controller_node_name == 'localhost':
controller_node_name = self.session.xenapi.host.get_record(
util.get_this_host_ref(self.session)
)['hostname']
assert controller_node_name
assert controller_node_name != 'localhost'
controller_host = None
secondary_hosts = []
hosts = self.session.xenapi.host.get_all_records()
for host_ref, host_rec in hosts.items():
hostname = host_rec['hostname']
if controller_node_name == hostname:
controller_host = host_ref
else:
secondary_hosts.append((host_ref, hostname))
action_name = 'Starting' if enabled else 'Stopping'
if controller_node_name and not controller_host:
util.SMlog('Failed to find controller host: `{}`'.format(
controller_node_name
))
if enabled and controller_host:
util.SMlog('{} drbd-reactor on controller host `{}`...'.format(
action_name, controller_node_name
))
# If enabled is true, we try to start the controller on the desired
# node name first.
self._update_drbd_reactor(controller_host, enabled)
for host_ref, hostname in secondary_hosts:
util.SMlog('{} drbd-reactor on host {}...'.format(
action_name, hostname
))
self._update_drbd_reactor(host_ref, enabled)
if not enabled and controller_host:
util.SMlog('{} drbd-reactor on controller host `{}`...'.format(
action_name, controller_node_name
))
# If enabled is false, we disable the drbd-reactor service of
# the controller host last. Why? Otherwise the linstor-controller
# of other nodes can be started, and we don't want that.
self._update_drbd_reactor(controller_host, enabled)
# --------------------------------------------------------------------------
# Metadata.
# --------------------------------------------------------------------------
def _synchronize_metadata_and_xapi(self):
try:
# First synch SR parameters.
self.update(self.uuid)
# Now update the VDI information in the metadata if required.
xenapi = self.session.xenapi
volumes_metadata = self._linstor.get_volumes_with_metadata()
for vdi_uuid, volume_metadata in volumes_metadata.items():
try:
vdi_ref = xenapi.VDI.get_by_uuid(vdi_uuid)
except Exception: