-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathlvm.py
2327 lines (1874 loc) · 79.9 KB
/
lvm.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
import functools
import random
import os
import os.path
import threading
import time
import traceback
import weakref
import re
import xml.etree.ElementTree as etree
import simplejson
from zstacklib.utils import form
from zstacklib.utils import shell
from zstacklib.utils import bash
from zstacklib.utils import lock
from zstacklib.utils import log
from zstacklib.utils import linux
from zstacklib.utils import thread
from zstacklib.utils import sanlock
from zstacklib.utils import remoteStorage
from cachetools import TTLCache
from distutils.version import LooseVersion
from zstacklib.utils.linux import get_fs_type
logger = log.get_logger(__name__)
LV_RESERVED_SIZE = 1024*1024*4
LVM_CONFIG_PATH = "/etc/lvm"
LVM_CONFIG_FILE = '/etc/lvm/lvm.conf'
SANLOCK_CONFIG_FILE_PATH = "/etc/sanlock/sanlock.conf"
DEB_SANLOCK_CONFIG_FILE_PATH = "/etc/default/sanlock"
LIVE_LIBVIRT_XML_DIR = "/var/run/libvirt/qemu"
SANLOCK_IO_TIMEOUT = 40
LVMLOCKD_LOG_FILE_PATH = "/var/log/lvmlockd/lvmlockd.log"
LVMLOCKD_LOG_RSYSLOG_PATH = "/etc/rsyslog.d/lvmlockd.conf"
LVMLOCKD_SERVICE_PATH = "/lib/systemd/system/lvm2-lvmlockd.service"
LVMLOCKD_LOG_LOGROTATE_PATH = "/etc/logrotate.d/lvmlockd"
LVMLOCKD_ADOPT_FILE = "/run/lvm/lvmlockd.adopt"
LVM_CONFIG_BACKUP_PATH = "/etc/lvm/zstack-backup"
LVM_CONFIG_ARCHIVE_PATH = "/etc/lvm/archive"
SUPER_BLOCK_BACKUP = "superblock.bak"
COMMON_TAG = "zs::sharedblock"
VOLUME_TAG = COMMON_TAG + "::volume"
IMAGE_TAG = COMMON_TAG + "::image"
ENABLE_DUP_GLOBAL_CHECK = False
LVMLOCKD_VERSION = None
thinProvisioningInitializeSize = "thinProvisioningInitializeSize"
ONE_HOUR_IN_SEC = 60 * 60
lv_offset = TTLCache(maxsize=100, ttl=ONE_HOUR_IN_SEC)
class VolumeProvisioningStrategy(object):
ThinProvisioning = "ThinProvisioning"
ThickProvisioning = "ThickProvisioning"
class VmStruct(object):
def __init__(self):
super(VmStruct, self).__init__()
self.pid = ""
self.xml = ""
self.root_volume = ""
self.uuid = ""
self.volumes = []
def load_from_xml(self, xml):
def load_source(element):
is_root_vol = False
path = None
for e in element:
if e.tag == "boot":
is_root_vol = True
elif e.tag == "source":
if "file" in e.attrib:
path = e.attrib["file"]
elif "dev" in e.attrib:
path = e.attrib["dev"]
if path and path.startswith("/dev/"):
self.volumes.append(path)
if is_root_vol:
self.root_volume = path
self.xml = xml
root = etree.fromstring(xml)
for e1 in root:
if e1.tag == "domain":
for e2 in e1:
if e2.tag == "devices":
for e3 in e2:
if e3.tag == "disk":
load_source(e3)
return
class LvmlockdLockType(object):
NULL = 0
SHARE = 1
EXCLUSIVE = 2
@staticmethod
def from_abbr(abbr, raise_exception=False):
if abbr.strip() == "sh":
return LvmlockdLockType.SHARE
elif abbr.strip() == "ex":
return LvmlockdLockType.EXCLUSIVE
elif abbr.strip() == "un":
return LvmlockdLockType.NULL
elif abbr.strip() == "":
if raise_exception:
raise RetryException("can not get locking type sice it is active without lvmlock info")
logger.warn("can not get correct lvm lock type! use null as a safe choice")
return LvmlockdLockType.NULL
else:
raise Exception("unknown lock type from abbr: %s" % abbr)
@staticmethod
def from_str(string):
if string == "NULL":
return LvmlockdLockType.SHARE
elif string == "SHARE":
return LvmlockdLockType.EXCLUSIVE
elif string == "EXCLUSIVE":
return LvmlockdLockType.NULL
else:
raise Exception("unknown lock type from str: %s" % string)
class RetryException(Exception):
pass
class SharedBlockCandidateStruct:
def __init__(self):
self.wwid = None # type: str
self.vendor = None # type: str
self.model = None # type: str
self.wwn = None # type: str
self.serial = None # type: str
self.hctl = None # type: str
self.type = None # type: str
self.size = None # type: long
self.path = None # type: str
def get_vg_uuid(path):
# type: (str) -> str
if not path or len(path.split("/")) != 4:
raise Exception("invalid lv path[%s]" % path)
return path.split("/")[2]
def get_block_devices():
scsi_info = get_lsscsi_info()
# 1. get multi path devices information
block_devices, slave_devices = get_mpath_block_devices(scsi_info)
# 2. get information of other devices
block_devices.extend(get_disk_block_devices(slave_devices, scsi_info))
# 3. get nvme block devices
block_devices.extend(get_nvme_block_devices())
return block_devices
def get_nvme_block_devices():
if not os.path.exists('/usr/sbin/nvme') and not os.path.exists('/sbin/nvme'):
return []
s = shell.ShellCmd("nvme list -o json")
s(False)
if s.return_code != 0:
return []
try:
devices = []
ret = simplejson.loads(s.stdout)
for d in ret.get("Devices", []):
dev = os.path.basename(d.get("DevicePath", ""))
if not dev or not os.path.exists("/sys/block/%s/wwid" % dev):
continue
wwid = linux.read_file("/sys/block/%s/wwid" % dev)
if wwid:
devices.append(get_device_info(dev, {dev: wwid.strip()}))
return devices
except Exception as e:
logger.error(traceback.format_exc())
return []
@bash.in_bash
def get_mpath_block_devices(scsi_info):
slave_devices = []
mpath_devices = []
cmd = shell.ShellCmd("multipath -l -v1")
cmd(is_exception=False)
if cmd.return_code == 0 and cmd.stdout.strip() != "":
mpath_devices = cmd.stdout.strip().splitlines()
block_devices_list = [None] * len(mpath_devices)
def get_slave_block_devices(slave, dm, i):
try:
struct = get_device_info(slave, scsi_info)
if struct is None:
return
struct.type = "mpath"
block_devices_list[i] = struct
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
return
threads = []
for idx, mpath_device in enumerate(mpath_devices, start=0):
try:
dm = os.path.basename(os.path.realpath("/dev/mapper/%s" % mpath_device))
if not dm.startswith("dm-"):
continue
slaves = os.listdir("/sys/class/block/%s/slaves/" % dm)
if slaves is None or len(slaves) == 0:
struct = SharedBlockCandidateStruct()
struct.wwid = get_dm_wwid(dm)
struct.type = "mpath"
block_devices_list[idx] = struct
continue
slave_devices.extend(slaves)
threads.append(thread.ThreadFacade.run_in_thread(get_slave_block_devices, [slaves[0], dm, idx]))
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
continue
for t in threads:
t.join()
return filter(None, block_devices_list), slave_devices
def get_disk_block_devices(slave_devices, scsi_info):
disks = shell.call("lsblk -p -o NAME,TYPE | awk '/disk/{print $1}'").strip().split()
block_devices_list = [None] * len(disks)
slave_multipaths = shell.call("multipath -l | grep -A 1 policy | grep -v policy |awk -F - '{print $2}'| awk '{print $2}'").strip().splitlines()
slave_multipaths = filter(None, slave_multipaths)
is_multipath_running_sign = is_multipath_running()
def get_block_device_info(disk, i):
try:
struct = get_device_info(disk.strip().split("/")[-1], scsi_info)
if struct is None:
return
if bash.bash_r('wipefs -n %s | grep LVM2 > /dev/null' % disk.strip()) == 0:
struct.type = "lvm-pv"
block_devices_list[i] = struct
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
return
threads = []
for idx, disk in enumerate(disks, start=0):
try:
if disk.split("/")[-1] in slave_devices or is_slave_of_multipath_list(disk, slave_multipaths, is_multipath_running_sign):
continue
threads.append(thread.ThreadFacade.run_in_thread(get_block_device_info, [disk, idx]))
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
continue
for t in threads:
t.join()
return filter(None, block_devices_list)
def get_lsscsi_info():
scsi_info = {}
o = filter(lambda s: "/dev/" in s, run_lsscsi_i())
for info in o:
dev_and_wwid = info.split("/dev/")[1].split(" ")
dev_name = dev_and_wwid[0]
wwid = dev_and_wwid[-1]
if not wwid or wwid == "-":
continue
scsi_info[dev_name] = wwid
return scsi_info
def run_lsscsi_i():
if os.path.exists("/usr/lib/udev/scsi_id"):
return bash.bash_o("""lsscsi | awk '{printf $0" "; system("/usr/lib/udev/scsi_id -g -u -d "$NF" || echo '-'");}'""").strip().splitlines()
else:
return bash.bash_o("lsscsi -i").strip().splitlines()
def is_multipath_running():
r = bash.bash_r("multipath -t > /dev/null")
if r != 0:
return False
r = bash.bash_r("pgrep multipathd")
if r != 0:
return False
return True
@bash.in_bash
def is_slave_of_multipath(dev_path):
# type: (str) -> bool
if is_multipath_running() is False:
return False
r = bash.bash_r("multipath -c %s" % dev_path)
return r == 0
def is_slave_of_multipath_list(dev_path, slave_multipath, is_multipath_running_sign):
if is_multipath_running_sign is False:
return False
if dev_path.split("/")[-1] in slave_multipath:
return True
else:
return False
def is_multipath(dev_name):
if not is_multipath_running():
return False
r = bash.bash_r("multipath /dev/%s -l | grep policy" % dev_name)
if r == 0:
return True
slaves = linux.listdir("/sys/class/block/%s/slaves/" % dev_name)
if slaves is not None and len(slaves) > 0:
if len(slaves) == 1 and slaves[0] == "":
return False
return True
return False
def get_multipath_dmname(dev_name):
# if is multipath dev, return;
# if is one of multipath paths, return multipath dev(dm-xxx);
# else return None
slaves = linux.listdir("/sys/class/block/%s/slaves/" % dev_name)
if slaves is not None and len(slaves) > 0 and slaves[0].strip() != "":
return dev_name
r = bash.bash_r("multipath /dev/%s -l | grep policy" % dev_name)
if r != 0:
return None
return bash.bash_o("multipath -l /dev/%s | head -n1 | grep -Eo 'dm-[[:digits:]]+'" % dev_name).strip()
def get_multipath_name(dev_name):
return bash.bash_o("multipath /dev/%s -l -v1" % dev_name).strip()
def get_lvmlockd_service_name():
service_name = 'lvm2-lvmlockd.service'
if LooseVersion(get_lvmlockd_version()) > LooseVersion("2.02"):
service_name = 'lvmlockd.service'
return service_name
def get_lvmlockd_version():
global LVMLOCKD_VERSION
if LVMLOCKD_VERSION is None:
LVMLOCKD_VERSION = shell.call("""lvmlockd --version | awk '{print $3}' | awk -F'.' '{print $1"."$2}'""").strip()
return LVMLOCKD_VERSION
def get_running_lvmlockd_version():
pid = get_lvmlockd_pid()
if pid:
exe = "/proc/%s/exe" % pid
return shell.call("""%s --version | awk '{print $3}' | awk -F'.' '{print $1"."$2}'""" % exe).strip()
def get_lvmlockd_pid():
return linux.find_process_by_command('lvmlockd')
def get_dm_wwid(dm):
try:
stdout = shell.call("set -o pipefail; udevadm info -n %s | grep -o 'dm-uuid-mpath-\S*' | awk -F '-' '{print $NF; exit}'" % dm)
return stdout.strip().strip("()")
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
return None
def get_device_info(dev_name, scsi_info):
# type: (str, dict[str, str]) -> SharedBlockCandidateStruct
s = SharedBlockCandidateStruct()
dev_name = dev_name.strip()
def get_wwid(dev):
try:
if dev in scsi_info.keys():
return scsi_info[dev]
elif dev.startswith("dm-"):
return get_dm_wwid(dev)
else:
return None
except Exception as e:
logger.warn(linux.get_exception_stacktrace())
return None
s = lsblk_info(dev_name)
if not s:
return s
wwid = get_wwid(dev_name)
if not wwid or wwid == "-":
return None
s.wwid = wwid
s.path = get_device_path(dev_name)
return s
def lsblk_info(dev_name):
# type: (str) -> SharedBlockCandidateStruct
s = SharedBlockCandidateStruct()
r, o, e = bash.bash_roe("lsblk --pair -b -p -o NAME,VENDOR,MODEL,WWN,SERIAL,HCTL,TYPE,SIZE /dev/%s" % dev_name,
False)
if r != 0 or o.strip() == "":
logger.warn("can not get device information from %s" % dev_name)
return None
def get_data(e):
return e.split("=")[1].strip().strip('"')
for entry in o.strip().split("\n")[0].split('" '): # type: str
if entry.startswith("VENDOR"):
s.vendor = get_data(entry)
elif entry.startswith("MODEL"):
s.model = get_data(entry)
elif entry.startswith("WWN"):
s.wwn = get_data(entry)
elif entry.startswith("SERIAL"):
s.serial = get_data(entry)
elif entry.startswith('HCTL'):
s.hctl = get_data(entry)
elif entry.startswith('SIZE'):
s.size = get_data(entry)
elif entry.startswith('TYPE'):
s.type = get_data(entry)
return s
def get_device_path(dev):
for symlink in shell.call("udevadm info -q symlink -n %s" % dev).strip().split():
if 'by-path' in symlink:
return os.path.basename(symlink)
def calcLvReservedSize(size):
# NOTE(weiw): Add additional 12M for every lv
size = int(size) + 3 * LV_RESERVED_SIZE
# NOTE(weiw): Add additional 4M per 4GB for qcow2 potential use
size = int(size) + (size/1024/1024/1024/4) * LV_RESERVED_SIZE
return size
def getOriginalSize(size):
size = int(size) - (int(size) / 1024 / 1024 / 1024 / 4) * LV_RESERVED_SIZE
size = int(size) - 3 * LV_RESERVED_SIZE
return size
def check_lvm_config_is_default():
cmd = shell.ShellCmd("lvmconfig --type diff")
cmd(is_exception=True)
if cmd.stdout != "":
return False
else:
return True
def clean_duplicate_configs():
cmd = shell.ShellCmd("md5sum %s/* " % LVM_CONFIG_BACKUP_PATH +
" | awk 'p[$1]++ { printf \"rm %s\\n\",$2;}' | bash")
cmd(is_exception=False)
def backup_lvm_config():
if not os.path.exists(LVM_CONFIG_PATH):
logger.warn("can not find lvm config path: %s, backup failed" % LVM_CONFIG_PATH)
return
if not os.path.exists(LVM_CONFIG_BACKUP_PATH):
os.makedirs(LVM_CONFIG_BACKUP_PATH)
clean_duplicate_configs()
current_time = time.time()
cmd = shell.ShellCmd("cp %s/lvm.conf %s/lvm-%s.conf; "
"cp %s/lvmlocal.conf %s/lvmlocal-%s.conf" %
(LVM_CONFIG_PATH, LVM_CONFIG_BACKUP_PATH, current_time,
LVM_CONFIG_PATH, LVM_CONFIG_BACKUP_PATH, current_time))
cmd(is_exception=False)
logger.debug("backup lvm config file success")
def reset_lvm_conf_default():
if not os.path.exists(LVM_CONFIG_PATH):
raise Exception("can not find lvm config path: %s, reset lvm config failed" % LVM_CONFIG_PATH)
cmd = shell.ShellCmd("lvmconfig --type default > %s/lvm.conf; "
"lvmconfig --type default > %s/lvmlocal.conf" %
(LVM_CONFIG_PATH, LVM_CONFIG_PATH))
cmd(is_exception=False)
def config_lvm_by_sed(keyword, entry, files):
if not os.path.exists(LVM_CONFIG_PATH):
raise Exception("can not find lvm config path: %s, config lvm failed" % LVM_CONFIG_PATH)
for f in files:
cmd = shell.ShellCmd("sed -i 's/.*\\b%s\\b.*/%s/g' %s/%s" %
(keyword, entry, LVM_CONFIG_PATH, f))
cmd(is_exception=False)
logger.debug(bash.bash_o("lvmconfig --type diff"))
@bash.in_bash
def config_lvm_filter(files, no_drbd=False, preserve_disks=None):
# type: (list[str], bool, set[str]) -> object
if not os.path.exists(LVM_CONFIG_PATH):
raise Exception("can not find lvm config path: %s, config lvm failed" % LVM_CONFIG_PATH)
if preserve_disks is not None and len(preserve_disks) != 0:
filter_str = 'filter=['
for disk in preserve_disks:
filter_str += '"a|^%s$|", ' % disk.replace("/", "\\/")
filter_str += '"r\/.*\/"]'
for f in files:
bash.bash_r("sed -i 's/.*\\b%s.*/%s/g' %s/%s" % ("filter", filter_str, LVM_CONFIG_PATH, f))
bash.bash_r("sed -i 's/.*\\b%s.*/global_%s/g' %s/%s" % ("global_filter", filter_str, LVM_CONFIG_PATH, f))
linux.sync_file(LVM_CONFIG_FILE)
return
filter_str = 'filter=["r|\\/dev\\/cdrom|"'
vgs = bash.bash_o("vgs --nolocking -t -oname --noheading").splitlines()
for vg in vgs:
filter_str += ', "r\\/dev\\/mapper\\/%s.*\\/"' % vg.strip()
if no_drbd:
filter_str += ', "r\\/dev\\/drbd.*\\/"'
filter_str += ']'
for f in files:
bash.bash_r("sed -i 's/.*\\b%s.*/%s/g' %s/%s" % ("filter", filter_str, LVM_CONFIG_PATH, f))
linux.sync_file(LVM_CONFIG_FILE)
def modify_sanlock_config(key, value):
if not os.path.exists(SANLOCK_CONFIG_FILE_PATH) and os.path.exists(DEB_SANLOCK_CONFIG_FILE_PATH):
global SANLOCK_CONFIG_FILE_PATH
SANLOCK_CONFIG_FILE_PATH = DEB_SANLOCK_CONFIG_FILE_PATH
if not os.path.exists(os.path.dirname(SANLOCK_CONFIG_FILE_PATH)):
linux.mkdir(os.path.dirname(SANLOCK_CONFIG_FILE_PATH))
if not os.path.exists(SANLOCK_CONFIG_FILE_PATH):
raise Exception("can not find sanlock config path: %s, config sanlock failed" % SANLOCK_CONFIG_FILE_PATH)
with open(SANLOCK_CONFIG_FILE_PATH,'r') as r:
lines=r.readlines()
with open(SANLOCK_CONFIG_FILE_PATH,'w') as w:
value_with_key = key + ' = ' + str(value)
find_key = False
need_delete_line = False
for line in lines:
# pure_line is line without comment and space
pure_line = line.replace('#', '')
pure_line = pure_line.replace(' ', '')
if pure_line.startswith(key):
if find_key is True:
# more than one key in config file, so delete it
need_delete_line = True
else:
find_key = True
line = line.replace(line, value_with_key)
if need_delete_line is False:
# change line: modify value if key exist && unique
w.write(value_with_key)
w.write('\n')
else:
# do nothing to delete, and reset the value
need_delete_line = False
else:
w.write(line)
if find_key is False:
# change line: add "key = value" if key not exist
w.write('\n')
w.write(value_with_key)
def config_lvmlockd(io_timeout=40):
content = """[Unit]
Description=LVM2 lock daemon
Documentation=man:lvmlockd(8)
After=lvm2-lvmetad.service
[Service]
Type=simple
NonBlocking=true
ExecStart=/sbin/lvmlockd --daemon-debug --sanlock-timeout %s --adopt 1
StandardError=syslog
StandardOutput=syslog
SyslogIdentifier=lvmlockd
Environment=SD_ACTIVATION=1
PIDFile=/run/lvmlockd.pid
SendSIGKILL=no
[Install]
WantedBy=multi-user.target
""" % io_timeout
lvmlockd_service_path = os.path.join("/lib/systemd/system", get_lvmlockd_service_name())
with open(lvmlockd_service_path, 'w') as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.chmod(lvmlockd_service_path, 0o644)
if not os.path.exists(LVMLOCKD_LOG_RSYSLOG_PATH):
content = """if $programname == 'lvmlockd' then %s
& stop
""" % LVMLOCKD_LOG_FILE_PATH
with open(LVMLOCKD_LOG_RSYSLOG_PATH, 'w') as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.chmod(LVMLOCKD_LOG_RSYSLOG_PATH, 0o644)
shell.call("systemctl restart rsyslog", exception=False)
cmd = shell.ShellCmd("systemctl daemon-reload")
cmd(is_exception=False)
def config_lvm_conf(node, value):
cmd = shell.ShellCmd("lvmconfig --mergedconfig --config %s=%s -f /etc/lvm/lvm.conf" % (node, value))
cmd(is_exception=True)
def config_lvmlocal_conf(node, value):
cmd = shell.ShellCmd("lvmconfig --mergedconfig --config %s=%s -f /etc/lvm/lvmlocal.conf" % (node, value))
cmd(is_exception=True)
@bash.in_bash
def start_lvmlockd(io_timeout=40):
if not os.path.exists(os.path.dirname(LVMLOCKD_LOG_FILE_PATH)):
os.mkdir(os.path.dirname(LVMLOCKD_LOG_FILE_PATH))
config_lvmlockd(io_timeout)
running_lockd_version = get_running_lvmlockd_version()
if running_lockd_version and LooseVersion(running_lockd_version) < LooseVersion(get_lvmlockd_version()):
write_lvmlockd_adopt_file()
stop_lvmlockd()
for service in ["sanlock", get_lvmlockd_service_name()]:
cmd = shell.ShellCmd("timeout 30 systemctl start %s" % service)
cmd(is_exception=True)
content = """/var/log/lvmlockd/lvmlockd.log {
rotate 15
missingok
copytruncate
size 30M
su root root
compress
compresscmd /usr/bin/xz
uncompresscmd /usr/bin/unxz
compressext .xz
}"""
with open(LVMLOCKD_LOG_LOGROTATE_PATH, 'w') as f:
f.write(content)
f.flush()
os.fsync(f.fileno())
os.chmod(LVMLOCKD_LOG_LOGROTATE_PATH, 0o644)
def write_lvmlockd_adopt_file():
def _get_lockspace_name(line):
return line.split()[1].split(":")[0]
class Lock:
def __init__(self, line):
## line format: r lvm_8c8b0ad64b0e42f4a9792db1f2bbacd8:OGDB3v-DKJ9-kdYX-XO7p-7cEp-jK22-jm1sgp:/dev/mapper/8c8b0ad64b0e42f4a9792db1f2bbacd8-lvmlock:70254592:1 p 60836
self.line = line
def get_lockspace(self):
return self.line.split()[1].split(":")[0]
def get_uuid(self):
return self.line.split()[1].split(":")[1]
def get_path(self):
return self.line.split()[1].split(":")[2]
def get_offset(self):
return self.line.split()[1].split(":")[3]
def get_mode(self):
return self.line.split()[1].split(":")[4]
def _build_lvmlockd_adopt_file(all_locks):
content = ""
for lockspace in all_locks:
VG_NAME = lockspace.replace("lvm_", "")
VG_UUID = get_vg_lvm_uuid(VG_NAME)
vg = "VG: %s %s sanlock 1.0.0:lvmlock\n" % (VG_UUID, VG_NAME)
content += vg
for resource in all_locks.get(lockspace):
lv = "LV: %s %s 1.0.0:%s %s 0\n" % (VG_UUID, resource.get_uuid(), resource.get_offset(), "sh "if resource.get_mode() == "SH" else "ex")
content += lv
if len(content) != 0:
logger.debug("write sanlock records to %s, content : \n%s" % (LVMLOCKD_ADOPT_FILE, content))
linux.write_file(LVMLOCKD_ADOPT_FILE, content, create_if_not_exist=True)
lines = bash.bash_o("sanlock client status").splitlines()
all_locks = {}
for line in lines:
if line.startswith("s "):
all_locks.update({_get_lockspace_name(line) : []})
elif line.startswith("r "):
all_locks.get(_get_lockspace_name(line)).append(Lock(line))
_build_lvmlockd_adopt_file(all_locks)
@bash.in_bash
def stop_lvmlockd():
pid = get_lvmlockd_pid()
if pid:
linux.kill_process(pid)
@bash.in_bash
def start_vg_lock(vgUuid, retry_times_for_checking_vg_lockspace):
@linux.retry(times=60, sleep_time=random.uniform(1, 10))
def vg_lock_is_adding(vgUuid):
# NOTE(weiw): this means vg locking is adding rather than complete
return_code = bash.bash_r("sanlock client status | grep -E 's lvm_%s.*\\:0 ADD'" % vgUuid)
if return_code == 0:
raise RetryException("vg %s lock space is starting" % vgUuid)
return False
@linux.retry(times=retry_times_for_checking_vg_lockspace, sleep_time=random.uniform(0.1, 2))
def vg_lock_exists(vgUuid):
return_code = bash.bash_r("lvmlockctl -i | grep %s" % vgUuid)
if return_code != 0:
raise RetryException("can not find lock space for vg %s via lvmlockctl" % vgUuid)
elif vg_lock_is_adding(vgUuid) is True:
raise RetryException("lock space for vg %s is adding" % vgUuid)
else:
return True
@linux.retry(times=5, sleep_time=random.uniform(0.1, 10))
def start_lock(vgUuid):
modify_sanlock_config("use_zstack_vglock_timeout", 1)
modify_sanlock_config("use_zstack_vglock_large_delay", 1)
r, o, e = bash.bash_roe("vgchange --lock-start %s" % vgUuid)
modify_sanlock_config("use_zstack_vglock_timeout", 0)
modify_sanlock_config("use_zstack_vglock_large_delay", 0)
if r != 0:
if "Device or resource busy" in o+e:
bash.bash_roe("dmsetup remove %s-lvmlock" % vgUuid)
raise Exception("vgchange --lock-start failed: return code: %s, stdout: %s, stderr: %s" %
(r, o, e))
vg_lock_exists(vgUuid)
try:
vg_lock_exists(vgUuid)
except RetryException:
start_lock(vgUuid)
except Exception as e:
raise e
def stop_vg_lock(vgUuid):
@linux.retry(times=3, sleep_time=random.uniform(0.1, 1))
def vg_lock_not_exists(vgUuid):
cmd = shell.ShellCmd("lvmlockctl -i | grep %s" % vgUuid)
cmd(is_exception=False)
if cmd.return_code == 0:
raise RetryException("lock space for vg %s still exists" % vgUuid)
else:
return True
@linux.retry(times=15, sleep_time=random.uniform(0.1, 30))
def stop_lock(vgUuid):
cmd = shell.ShellCmd("vgchange --lock-stop %s" % vgUuid)
cmd(is_exception=True)
if cmd.return_code != 0:
raise Exception("vgchange --lock-stop failed")
vg_lock_not_exists(vgUuid)
try:
vg_lock_not_exists(vgUuid)
except RetryException:
stop_lock(vgUuid)
except Exception as e:
raise e
@bash.in_bash
def clean_lvm_archive_files(vgUuid):
if not os.path.exists(LVM_CONFIG_ARCHIVE_PATH):
logger.warn("can not find lvm archive path %s" % LVM_CONFIG_ARCHIVE_PATH)
return
archive_files = len([f for f in os.listdir(LVM_CONFIG_ARCHIVE_PATH) if vgUuid in f])
if archive_files > 10:
bash.bash_r("ls -rt %s | grep %s | head -n %s | xargs -i rm -rf %s/{}" % (LVM_CONFIG_ARCHIVE_PATH, vgUuid, archive_files-10, LVM_CONFIG_ARCHIVE_PATH))
@bash.in_bash
def quitLockServices():
bash.bash_roe("sanlock client shutdown")
bash.bash_roe("timeout 30 systemctl stop sanlock.service")
bash.bash_roe("lvmlockctl -q")
@bash.in_bash
def drop_vg_lock(vgUuid):
bash.bash_roe("lvmlockctl --gl-disable %s" % vgUuid)
bash.bash_roe("lvmlockctl --drop %s" % vgUuid)
@bash.in_bash
def get_vg_lvm_uuid(vgUuid):
return bash.bash_o("vgs --nolocking -t --noheading -ouuid %s" % vgUuid).strip()
def get_running_host_id(vgUuid):
cmd = shell.ShellCmd("sanlock client gets | awk -F':' '/%s/{ print $2 }'" % vgUuid)
cmd(is_exception=False)
if cmd.stdout.strip() == "":
raise Exception("can not get running host id for vg %s" % vgUuid)
return cmd.stdout.strip()
def get_wwid(disk_path):
cmd = shell.ShellCmd("udevadm info --name=%s | grep 'disk/by-id.*' -m1 -o | awk -F '/' {' print $3 '}" % disk_path)
cmd(is_exception=False)
return cmd.stdout.strip()
@bash.in_bash
def backup_super_block(disk_path):
wwid = get_wwid(disk_path)
if wwid is None or wwid == "":
logger.warn("can not get wwid of disk %s" % disk_path)
current_time = time.time()
disk_back_file = os.path.join(LVM_CONFIG_BACKUP_PATH, "%s.%s.%s" % (wwid, SUPER_BLOCK_BACKUP, current_time))
bash.bash_roe("dd if=%s of=%s bs=64KB count=1 conv=notrunc" % (disk_path, disk_back_file))
return disk_back_file
@bash.in_bash
def wipe_fs(disks, expected_vg=None, with_lock=True):
@bash.in_bash
def clear_lvmlock(vg_name):
bash.bash_r("lvmlockctl -D %s; lvmlockctl -k %s; lvmlockctl -r %s" % (vg_name, vg_name, vg_name))
for disk in disks:
exists_vg = None
r, o = bash.bash_ro("pvs --nolocking -t --noheading -o vg_name %s" % disk)
if r == 0 and o.strip() != "":
exists_vg = o.strip()
if expected_vg in o.strip():
continue
backup = backup_super_block(disk)
if bash.bash_r("grep %s %s" % (expected_vg, backup)) == 0:
raise Exception("found vg uuid in superblock backup while not found in lvm command!")
need_flush_mpath = False
bash.bash_roe("partprobe -s %s" % disk)
cmd_type = bash.bash_o("lsblk %s -oTYPE | grep mpath" % disk)
if cmd_type.strip() != "":
need_flush_mpath = True
if exists_vg is not None:
thread.ThreadFacade.run_in_thread(clear_lvmlock, [exists_vg])
time.sleep(1)
bash.bash_roe("wipefs -af %s" % disk)
for holder in get_disk_holders([disk.split("/")[-1]]):
if not holder.startswith("dm-"):
continue
bash.bash_roe("dmsetup remove /dev/%s" % holder)
if need_flush_mpath:
bash.bash_roe("multipath -f %s && systemctl reload multipathd.service && sleep 1" % disk)
if exists_vg is not None:
bash.bash_r("grep -l %s /etc/drbd.d/* | xargs rm" % exists_vg)
logger.debug("found vg %s exists on this pv %s, start wipe" %
(exists_vg, disk))
try:
if with_lock:
drop_vg_lock(exists_vg)
remove_device_map_for_vg(exists_vg)
finally:
pass
def get_disk_holders(disk_names):
holders = []
for disk_name in disk_names:
h = linux.listdir("/sys/class/block/%s/holders/" % disk_name)
if len(h) == 0:
continue
holders.extend(h)
holders.extend(get_disk_holders(h))
holders.reverse()
return holders
@bash.in_bash
@linux.retry(times=5, sleep_time=random.uniform(0.1, 3))
def add_pv(vg_uuid, disk_path, metadata_size):
bash.bash_errorout("vgextend --metadatasize %s %s %s" % (metadata_size, vg_uuid, disk_path))
if bash.bash_r("pvs --nolocking -t --readonly %s | grep %s" % (disk_path, vg_uuid)):
raise Exception("disk %s not added to vg %s after vgextend" % (disk_path, vg_uuid))
def get_vg_size(vgUuid, raise_exception=True):
r, o, _ = bash.bash_roe("vgs --nolocking -t %s --noheadings --separator : --units b -o vg_size,vg_free,vg_lock_type" % vgUuid, errorout=raise_exception)
if r != 0:
return None, None
vg_size, vg_free = o.strip().split(':')[0].strip("B"), o.strip().split(':')[1].strip("B")
if "sanlock" in o:
return vg_size, vg_free
pools = get_thin_pools_from_vg(vgUuid)
if len(pools) == 0:
return vg_size, vg_free
vg_free = float(vg_free)
for pool in pools:
vg_free += pool.free
return vg_size, str(int(vg_free))
def get_all_vg_size():
# type: () -> dict[str, tuple[int, int]]
d = {}
o = bash.bash_o("vgs --nolocking -t %s --noheadings --separator : --units b -o name,vg_size,vg_free,vg_lock_type")
if not o:
return d
for line in o.splitlines():
xs = line.strip().split(':')
vg_name = xs[0]
vg_size = int(xs[1].strip("B"))
vg_free = int(xs[2].strip("B"))
if "sanlock" in line:
d[vg_name] = (vg_size, vg_free)
continue
pools = get_thin_pools_from_vg(vg_name)
if len(pools) == 0:
d[vg_name] = (vg_size, vg_free)
continue
for pool in pools:
vg_free += int(pool.free)
d[vg_name] = (vg_size, vg_free)
return d
def add_vg_tag(vgUuid, tag):
cmd = shell.ShellCmd("vgchange --addtag %s %s" % (tag, vgUuid))
cmd(is_exception=True)
def has_lv_tag(path, tag):
# type: (str, str) -> bool
if tag == "":
logger.debug("check tag is empty, return false")
return False
o = shell.call("lvs -Stags={%s} %s --nolocking -t --noheadings 2>/dev/null | wc -l" % (tag, path))
return o.strip() == '1'
def has_one_lv_tag_sub_string(path, tags):
# type: (str, list) -> bool
if not tags or len(tags) == 0:
logger.debug("check tag is empty, return false")
return False
exists_tags = set(shell.call("lvs %s -otags --nolocking -t --noheadings" % path).strip().split(","))
for tag in tags:
for exists_tag in exists_tags:
if tag in exists_tag:
return True
return False