forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcleanup.py
More file actions
executable file
·4555 lines (3952 loc) · 166 KB
/
Copy pathcleanup.py
File metadata and controls
executable file
·4555 lines (3952 loc) · 166 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/python3
#
# Copyright (C) Citrix Systems Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only.
#
# 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Script to coalesce and garbage collect COW-based SR's in the background
#
from sm_typing import Any, Dict, Optional, List, override
import os
import os.path
import sys
import time
import signal
import subprocess
import getopt
import datetime
import traceback
import base64
import zlib
import errno
import stat
import XenAPI # pylint: disable=import-error
import util
import lvutil
import lvmcache
import journaler
import fjournaler
import lock
import blktap2
import xs_errors
from refcounter import RefCounter
from ipc import IPCFlag
from lvmanager import LVActivator
from srmetadata import LVMMetadataHandler, VDI_TYPE_TAG
from functools import reduce
from time import monotonic as _time
from constants import NS_PREFIX_LVM, VG_LOCATION, VG_PREFIX
from cowutil import CowImageInfo, CowUtil, getCowUtil
from lvmcowutil import LV_PREFIX, LvmCowUtil
from vditype import VdiType, VdiTypeExtension, VDI_COW_TYPES, VDI_TYPE_TO_EXTENSION
try:
from linstorcowutil import LinstorCowUtil, MultiLinstorCowUtil
from linstorjournaler import LinstorJournaler
from linstorvolumemanager import get_controller_uri
from linstorvolumemanager import LinstorVolumeManager, LinstorVolumeManagerError, LinstorVolumeOpeners
from linstorvolumemanager import PERSISTENT_PREFIX as LINSTOR_PERSISTENT_PREFIX
LINSTOR_AVAILABLE = True
except ImportError:
LINSTOR_AVAILABLE = False
# Disable automatic leaf-coalescing. Online leaf-coalesce is currently not
# possible due to lvhd_stop_using_() not working correctly. However, we leave
# this option available through the explicit LEAFCLSC_FORCE flag in the VDI
# record for use by the offline tool (which makes the operation safe by pausing
# the VM first)
AUTO_ONLINE_LEAF_COALESCE_ENABLED = True
FLAG_TYPE_ABORT = "abort" # flag to request aborting of GC/coalesce
# process "lock", used simply as an indicator that a process already exists
# that is doing GC/coalesce on this SR (such a process holds the lock, and we
# check for the fact by trying the lock).
lockGCRunning = None
# process "lock" to indicate that the GC process has been activated but may not
# yet be running, stops a second process from being started.
LOCK_TYPE_GC_ACTIVE = "gc_active"
lockGCActive = None
# Default coalesce error rate limit, in messages per minute. A zero value
# disables throttling, and a negative value disables error reporting.
DEFAULT_COALESCE_ERR_RATE = 1.0 / 60
COALESCE_LAST_ERR_TAG = 'last-coalesce-error'
COALESCE_ERR_RATE_TAG = 'coalesce-error-rate'
VAR_RUN = "/var/run/"
SPEED_LOG_ROOT = VAR_RUN + "{uuid}.speed_log"
N_RUNNING_AVERAGE = 10
NON_PERSISTENT_DIR = '/run/nonpersistent/sm'
# Signal Handler
SIGTERM = False
class AbortException(util.SMException):
pass
class CancelException(util.SMException):
pass
def receiveSignal(signalNumber, frame):
global SIGTERM
util.SMlog("GC: recieved SIGTERM")
SIGTERM = True
return
################################################################################
#
# Util
#
class Util:
RET_RC = 1
RET_STDOUT = 2
RET_STDERR = 4
UUID_LEN = 36
PREFIX = {"G": 1024 * 1024 * 1024, "M": 1024 * 1024, "K": 1024}
@staticmethod
def log(text) -> None:
util.SMlog(text, ident="SMGC")
@staticmethod
def logException(tag):
info = sys.exc_info()
if info[0] == SystemExit:
# this should not be happening when catching "Exception", but it is
sys.exit(0)
tb = reduce(lambda a, b: "%s%s" % (a, b), traceback.format_tb(info[2]))
Util.log("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*")
Util.log(" ***********************")
Util.log(" * E X C E P T I O N *")
Util.log(" ***********************")
Util.log("%s: EXCEPTION %s, %s" % (tag, info[0], info[1]))
Util.log(tb)
Util.log("*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*")
@staticmethod
def doexec(args, expectedRC, inputtext=None, ret=None, log=True):
"Execute a subprocess, then return its return code, stdout, stderr"
proc = subprocess.Popen(args,
stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, \
shell=True, \
close_fds=True)
(stdout, stderr) = proc.communicate(inputtext)
stdout = str(stdout)
stderr = str(stderr)
rc = proc.returncode
if log:
Util.log("`%s`: %s" % (args, rc))
if type(expectedRC) != type([]):
expectedRC = [expectedRC]
if not rc in expectedRC:
reason = stderr.strip()
if stdout.strip():
reason = "%s (stdout: %s)" % (reason, stdout.strip())
Util.log("Failed: %s" % reason)
raise util.CommandException(rc, args, reason)
if ret == Util.RET_RC:
return rc
if ret == Util.RET_STDERR:
return stderr
return stdout
@staticmethod
def runAbortable(func, ret, ns, abortTest, pollInterval, timeOut, prefSig=signal.SIGKILL):
"""execute func in a separate thread and kill it if abortTest signals
so"""
abortSignaled = abortTest() # check now before we clear resultFlag
resultFlag = IPCFlag(ns)
resultFlag.clearAll()
pid = os.fork()
if pid:
startTime = _time()
try:
while True:
if resultFlag.test("success"):
Util.log(" Child process completed successfully")
resultFlag.clear("success")
return
if resultFlag.test("failure"):
resultFlag.clear("failure")
raise util.SMException("Child process exited with error")
if abortTest() or abortSignaled or SIGTERM:
os.killpg(pid, prefSig)
raise AbortException("Aborting due to signal")
if timeOut and _time() - startTime > timeOut:
os.killpg(pid, prefSig)
resultFlag.clearAll()
raise util.SMException("Timed out")
time.sleep(pollInterval)
finally:
wait_pid = 0
rc = -1
count = 0
while wait_pid == 0 and count < 10:
wait_pid, rc = os.waitpid(pid, os.WNOHANG)
if wait_pid == 0:
time.sleep(2)
count += 1
if wait_pid == 0:
Util.log("runAbortable: wait for process completion timed out")
else:
os.setpgrp()
try:
if func() == ret:
resultFlag.set("success")
else:
resultFlag.set("failure")
except Exception as e:
Util.log("Child process failed with : (%s)" % e)
resultFlag.set("failure")
Util.logException("This exception has occured")
os._exit(0)
@staticmethod
def num2str(number):
for prefix in ("G", "M", "K"):
if number >= Util.PREFIX[prefix]:
return "%.3f%s" % (float(number) / Util.PREFIX[prefix], prefix)
return "%s" % number
@staticmethod
def numBits(val):
count = 0
while val:
count += val & 1
val = val >> 1
return count
@staticmethod
def countBits(bitmap1, bitmap2):
"""return bit count in the bitmap produced by ORing the two bitmaps"""
len1 = len(bitmap1)
len2 = len(bitmap2)
lenLong = len1
lenShort = len2
bitmapLong = bitmap1
if len2 > len1:
lenLong = len2
lenShort = len1
bitmapLong = bitmap2
count = 0
for i in range(lenShort):
val = bitmap1[i] | bitmap2[i]
count += Util.numBits(val)
for i in range(i + 1, lenLong):
val = bitmapLong[i]
count += Util.numBits(val)
return count
@staticmethod
def getThisScript():
thisScript = util.get_real_path(__file__)
if thisScript.endswith(".pyc"):
thisScript = thisScript[:-1]
return thisScript
################################################################################
#
# XAPI
#
class XAPI:
USER = "root"
PLUGIN_ON_SLAVE = "on-slave"
CONFIG_SM = 0
CONFIG_OTHER = 1
CONFIG_ON_BOOT = 2
CONFIG_ALLOW_CACHING = 3
CONFIG_NAME = {
CONFIG_SM: "sm-config",
CONFIG_OTHER: "other-config",
CONFIG_ON_BOOT: "on-boot",
CONFIG_ALLOW_CACHING: "allow_caching"
}
class LookupError(util.SMException):
pass
def __init__(self, session, srUuid):
self.session = session
self._api_session = None
if self.session is None:
self._api_session = util.ApiSession("SM-GC")
self.session = self._api_session.session
self._srRef = self.session.xenapi.SR.get_by_uuid(srUuid)
self.srRecord = self.session.xenapi.SR.get_record(self._srRef)
self.hostUuid = util.get_this_host()
self._hostRef = self.session.xenapi.host.get_by_uuid(self.hostUuid)
self.task = None
self.task_progress = {"coalescable": 0, "done": 0}
def __del__(self):
if self._api_session:
self._api_session.logout()
@property
def srRef(self):
return self._srRef
def isPluggedHere(self):
pbds = self.getAttachedPBDs()
for pbdRec in pbds:
if pbdRec["host"] == self._hostRef:
return True
return False
def poolOK(self):
host_recs = self.session.xenapi.host.get_all_records()
for host_ref, host_rec in host_recs.items():
if not host_rec["enabled"]:
Util.log("Host %s not enabled" % host_rec["uuid"])
return False
return True
def isMaster(self):
if self.srRecord["shared"]:
pool = list(self.session.xenapi.pool.get_all_records().values())[0]
return pool["master"] == self._hostRef
else:
pbds = self.getAttachedPBDs()
if len(pbds) < 1:
raise util.SMException("Local SR not attached")
elif len(pbds) > 1:
raise util.SMException("Local SR multiply attached")
return pbds[0]["host"] == self._hostRef
def getAttachedPBDs(self):
"""Return PBD records for all PBDs of this SR that are currently
attached"""
attachedPBDs = []
pbds = self.session.xenapi.PBD.get_all_records()
for pbdRec in pbds.values():
if pbdRec["SR"] == self._srRef and pbdRec["currently_attached"]:
attachedPBDs.append(pbdRec)
return attachedPBDs
def getOnlineHosts(self):
return util.get_online_hosts(self.session)
def ensureInactive(self, hostRef, args):
text = self.session.xenapi.host.call_plugin( \
hostRef, self.PLUGIN_ON_SLAVE, "multi", args)
Util.log("call-plugin returned: '%s'" % text)
def getRecordHost(self, hostRef):
return self.session.xenapi.host.get_record(hostRef)
def _getRefVDI(self, uuid):
return self.session.xenapi.VDI.get_by_uuid(uuid)
def getRefVDI(self, vdi):
return self._getRefVDI(vdi.uuid)
def getRecordVDI(self, uuid):
try:
ref = self._getRefVDI(uuid)
return self.session.xenapi.VDI.get_record(ref)
except XenAPI.Failure:
return None
def singleSnapshotVDI(self, vdi):
return self.session.xenapi.VDI.snapshot(vdi.getRef(),
{"type": "internal"})
def forgetVDI(self, srUuid, vdiUuid):
"""Forget the VDI, but handle the case where the VDI has already been
forgotten (i.e. ignore errors)"""
try:
vdiRef = self.session.xenapi.VDI.get_by_uuid(vdiUuid)
self.session.xenapi.VDI.forget(vdiRef)
except XenAPI.Failure:
pass
def getConfigVDI(self, vdi, key):
kind = vdi.CONFIG_TYPE[key]
if kind == self.CONFIG_SM:
cfg = self.session.xenapi.VDI.get_sm_config(vdi.getRef())
elif kind == self.CONFIG_OTHER:
cfg = self.session.xenapi.VDI.get_other_config(vdi.getRef())
elif kind == self.CONFIG_ON_BOOT:
cfg = self.session.xenapi.VDI.get_on_boot(vdi.getRef())
elif kind == self.CONFIG_ALLOW_CACHING:
cfg = self.session.xenapi.VDI.get_allow_caching(vdi.getRef())
else:
assert(False)
Util.log("Got %s for %s: %s" % (self.CONFIG_NAME[kind], vdi, repr(cfg)))
return cfg
def removeFromConfigVDI(self, vdi, key):
kind = vdi.CONFIG_TYPE[key]
if kind == self.CONFIG_SM:
self.session.xenapi.VDI.remove_from_sm_config(vdi.getRef(), key)
elif kind == self.CONFIG_OTHER:
self.session.xenapi.VDI.remove_from_other_config(vdi.getRef(), key)
else:
assert(False)
def addToConfigVDI(self, vdi, key, val):
kind = vdi.CONFIG_TYPE[key]
if kind == self.CONFIG_SM:
self.session.xenapi.VDI.add_to_sm_config(vdi.getRef(), key, val)
elif kind == self.CONFIG_OTHER:
self.session.xenapi.VDI.add_to_other_config(vdi.getRef(), key, val)
else:
assert(False)
def isSnapshot(self, vdi):
return self.session.xenapi.VDI.get_is_a_snapshot(vdi.getRef())
def markCacheSRsDirty(self):
sr_refs = self.session.xenapi.SR.get_all_records_where( \
'field "local_cache_enabled" = "true"')
for sr_ref in sr_refs:
Util.log("Marking SR %s dirty" % sr_ref)
util.set_dirty(self.session, sr_ref)
def srUpdate(self):
Util.log("Starting asynch srUpdate for SR %s" % self.srRecord["uuid"])
abortFlag = IPCFlag(self.srRecord["uuid"])
task = self.session.xenapi.Async.SR.update(self._srRef)
cancelTask = True
try:
for i in range(60):
status = self.session.xenapi.task.get_status(task)
if not status == "pending":
Util.log("SR.update_asynch status changed to [%s]" % status)
cancelTask = False
return
if abortFlag.test(FLAG_TYPE_ABORT):
Util.log("Abort signalled during srUpdate, cancelling task...")
try:
self.session.xenapi.task.cancel(task)
cancelTask = False
Util.log("Task cancelled")
except:
pass
return
time.sleep(1)
finally:
if cancelTask:
self.session.xenapi.task.cancel(task)
self.session.xenapi.task.destroy(task)
Util.log("Asynch srUpdate still running, but timeout exceeded.")
def update_task(self):
self.session.xenapi.task.set_other_config(
self.task,
{
"applies_to": self._srRef
})
total = self.task_progress['coalescable'] + self.task_progress['done']
if (total > 0):
self.session.xenapi.task.set_progress(
self.task, float(self.task_progress['done']) / total)
def create_task(self, label, description):
self.task = self.session.xenapi.task.create(label, description)
self.update_task()
def update_task_progress(self, key, value):
self.task_progress[key] = value
if self.task:
self.update_task()
def set_task_status(self, status):
if self.task:
self.session.xenapi.task.set_status(self.task, status)
################################################################################
#
# VDI
#
class VDI(object):
"""Object representing a VDI of a COW-based SR"""
POLL_INTERVAL = 1
POLL_TIMEOUT = 30
DEVICE_MAJOR = 202
# config keys & values
DB_VDI_PARENT = "vhd-parent"
DB_VDI_TYPE = "vdi_type"
DB_VDI_BLOCKS = "vhd-blocks"
DB_VDI_PAUSED = "paused"
DB_VDI_RELINKING = "relinking"
DB_VDI_ACTIVATING = "activating"
DB_GC = "gc"
DB_COALESCE = "coalesce"
DB_LEAFCLSC = "leaf-coalesce" # config key
DB_GC_NO_SPACE = "gc_no_space"
LEAFCLSC_DISABLED = "false" # set by user; means do not leaf-coalesce
LEAFCLSC_FORCE = "force" # set by user; means skip snap-coalesce
LEAFCLSC_OFFLINE = "offline" # set here for informational purposes: means
# no space to snap-coalesce or unable to keep
# up with VDI. This is not used by the SM, it
# might be used by external components.
DB_ONBOOT = "on-boot"
ONBOOT_RESET = "reset"
DB_ALLOW_CACHING = "allow_caching"
CONFIG_TYPE = {
DB_VDI_PARENT: XAPI.CONFIG_SM,
DB_VDI_TYPE: XAPI.CONFIG_SM,
DB_VDI_BLOCKS: XAPI.CONFIG_SM,
DB_VDI_PAUSED: XAPI.CONFIG_SM,
DB_VDI_RELINKING: XAPI.CONFIG_SM,
DB_VDI_ACTIVATING: XAPI.CONFIG_SM,
DB_GC: XAPI.CONFIG_OTHER,
DB_COALESCE: XAPI.CONFIG_OTHER,
DB_LEAFCLSC: XAPI.CONFIG_OTHER,
DB_ONBOOT: XAPI.CONFIG_ON_BOOT,
DB_ALLOW_CACHING: XAPI.CONFIG_ALLOW_CACHING,
DB_GC_NO_SPACE: XAPI.CONFIG_SM
}
LIVE_LEAF_COALESCE_MAX_SIZE = 20 * 1024 * 1024 # bytes
LIVE_LEAF_COALESCE_TIMEOUT = 10 # seconds
TIMEOUT_SAFETY_MARGIN = 0.5 # extra margin when calculating
# feasibility of leaf coalesce
JRN_RELINK = "relink" # journal entry type for relinking children
JRN_COALESCE = "coalesce" # to communicate which VDI is being coalesced
JRN_LEAF = "leaf" # used in coalesce-leaf
STR_TREE_INDENT = 4
def __init__(self, sr, uuid, vdi_type):
self.sr = sr
self.scanError = True
self.uuid = uuid
self.vdi_type = vdi_type
self.fileName = ""
self.parentUuid = ""
self.sizeVirt = -1
self._sizePhys = -1
self._sizeAllocated = -1
self._hidden = False
self.parent = None
self.children = []
self._vdiRef = None
self.cowutil = getCowUtil(vdi_type)
self._clearRef()
@staticmethod
def extractUuid(path):
raise NotImplementedError("Implement in sub class")
def load(self, info=None) -> None:
"""Load VDI info"""
pass
def getDriverName(self) -> str:
return self.vdi_type
def getRef(self):
if self._vdiRef is None:
self._vdiRef = self.sr.xapi.getRefVDI(self)
return self._vdiRef
def getConfig(self, key, default=None):
config = self.sr.xapi.getConfigVDI(self, key)
if key == self.DB_ONBOOT or key == self.DB_ALLOW_CACHING:
val = config
else:
val = config.get(key)
if val:
return val
return default
def setConfig(self, key, val):
self.sr.xapi.removeFromConfigVDI(self, key)
self.sr.xapi.addToConfigVDI(self, key, val)
Util.log("Set %s = %s for %s" % (key, val, self))
def delConfig(self, key):
self.sr.xapi.removeFromConfigVDI(self, key)
Util.log("Removed %s from %s" % (key, self))
def ensureUnpaused(self):
if self.getConfig(self.DB_VDI_PAUSED) == "true":
Util.log("Unpausing VDI %s" % self)
self.unpause()
def pause(self, failfast=False) -> None:
if not blktap2.VDI.tap_pause(self.sr.xapi.session, self.sr.uuid,
self.uuid, failfast):
raise util.SMException("Failed to pause VDI %s" % self)
def _report_tapdisk_unpause_error(self):
try:
xapi = self.sr.xapi.session.xenapi
sr_ref = xapi.SR.get_by_uuid(self.sr.uuid)
msg_name = "failed to unpause tapdisk"
msg_body = "Failed to unpause tapdisk for VDI %s, " \
"VMs using this tapdisk have lost access " \
"to the corresponding disk(s)" % self.uuid
xapi.message.create(msg_name, "4", "SR", self.sr.uuid, msg_body)
except Exception as e:
util.SMlog("failed to generate message: %s" % e)
def unpause(self):
if not blktap2.VDI.tap_unpause(self.sr.xapi.session, self.sr.uuid,
self.uuid):
self._report_tapdisk_unpause_error()
raise util.SMException("Failed to unpause VDI %s" % self)
def refresh(self, ignoreNonexistent=True):
"""Pause-unpause in one step"""
self.sr.lock()
try:
try:
if not blktap2.VDI.tap_refresh(self.sr.xapi.session,
self.sr.uuid, self.uuid):
self._report_tapdisk_unpause_error()
raise util.SMException("Failed to refresh %s" % self)
except XenAPI.Failure as e:
if util.isInvalidVDI(e) and ignoreNonexistent:
Util.log("VDI %s not found, ignoring" % self)
return
raise
finally:
self.sr.unlock()
def isSnapshot(self):
return self.sr.xapi.isSnapshot(self)
def isAttachedRW(self):
return util.is_attached_rw(
self.sr.xapi.session.xenapi.VDI.get_sm_config(self.getRef()))
def getVDIBlocks(self):
val = self.updateBlockInfo()
bitmap = zlib.decompress(base64.b64decode(val))
return bitmap
def isCoalesceable(self):
"""A VDI is coalesceable if it has no siblings and is not a leaf"""
return (
not self.scanError and
self.parent and
len(self.parent.children) == 1 and
self.isHidden() and
len(self.children) > 0 and (
# Conditions below are Qcow2 specific:
# A Qcow2 chain can't be coalesce with more than one leaf attached.
# Put it another way, Qcow2 leaves activated on multiple hosts must
# prevent the coalesce of the chain.
self.vdi_type != VdiType.QCOW2 or
(self.vdi_type == VdiType.QCOW2 and len(self.sr.hasLeavesAttachedOn(self)) <= 1)
)
)
def isLeafCoalesceable(self):
"""A VDI is leaf-coalesceable if it has no siblings and is a leaf"""
return not self.scanError and \
self.parent and \
len(self.parent.children) == 1 and \
not self.isHidden() and \
len(self.children) == 0
def canLiveCoalesce(self, speed):
"""Can we stop-and-leaf-coalesce this VDI? The VDI must be
isLeafCoalesceable() already"""
feasibleSize = False
allowedDownTime = \
self.TIMEOUT_SAFETY_MARGIN * self.LIVE_LEAF_COALESCE_TIMEOUT
allocated_size = self.getAllocatedSize()
if speed:
feasibleSize = \
allocated_size // speed < allowedDownTime
else:
feasibleSize = \
allocated_size < self.LIVE_LEAF_COALESCE_MAX_SIZE
return (feasibleSize or
self.getConfig(self.DB_LEAFCLSC) == self.LEAFCLSC_FORCE)
def getAllPrunable(self):
if len(self.children) == 0: # base case
# it is possible to have a hidden leaf that was recently coalesced
# onto its parent, its children already relinked but not yet
# reloaded - in which case it may not be garbage collected yet:
# some tapdisks could still be using the file.
if self.sr.journaler.get(self.JRN_RELINK, self.uuid):
return []
if not self.scanError and self.isHidden():
return [self]
return []
thisPrunable = True
vdiList = []
for child in self.children:
childList = child.getAllPrunable()
vdiList.extend(childList)
if child not in childList:
thisPrunable = False
# We can destroy the current VDI if all childs are hidden BUT the
# current VDI must be hidden too to do that!
# Example in this case (after a failed live leaf coalesce):
#
# SMGC: [32436] SR 07ed ('linstor-nvme-sr') (2 VDIs in 1 VHD trees):
# SMGC: [32436] b5458d61(1.000G/4.127M)
# SMGC: [32436] *OLD_b545(1.000G/4.129M)
#
# OLD_b545 is hidden and must be removed, but b5458d61 not.
# Normally we are not in this function when the delete action is
# executed but in `_liveLeafCoalesce`.
if not self.scanError and not self.isHidden() and thisPrunable:
vdiList.append(self)
return vdiList
def getSizePhys(self) -> int:
return self._sizePhys
def getAllocatedSize(self) -> int:
return self._sizeAllocated
def getTreeRoot(self):
"Get the root of the tree that self belongs to"
root = self
while root.parent:
root = root.parent
return root
def getTreeHeight(self):
"Get the height of the subtree rooted at self"
if len(self.children) == 0:
return 1
maxChildHeight = 0
for child in self.children:
childHeight = child.getTreeHeight()
if childHeight > maxChildHeight:
maxChildHeight = childHeight
return maxChildHeight + 1
def getAllLeaves(self) -> List["VDI"]:
"Get all leaf nodes in the subtree rooted at self"
if len(self.children) == 0:
return [self]
leaves = []
for child in self.children:
leaves.extend(child.getAllLeaves())
return leaves
def updateBlockInfo(self) -> Optional[str]:
val = base64.b64encode(self._queryCowBlocks()).decode()
try:
self.setConfig(VDI.DB_VDI_BLOCKS, val)
except Exception:
if self.vdi_type != VdiType.QCOW2:
raise
# Sometime with QCOW2, our allocation table is too big to be stored in XAPI, in this case we do not store it
# and we write `skipped` instead so that hasWork is happy (and the GC doesn't run in loop indefinitely).
self.setConfig(VDI.DB_VDI_BLOCKS, "skipped")
return val
def rename(self, uuid) -> None:
"Rename the VDI file"
assert(not self.sr.vdis.get(uuid))
self._clearRef()
oldUuid = self.uuid
self.uuid = uuid
self.children = []
# updating the children themselves is the responsibility of the caller
del self.sr.vdis[oldUuid]
self.sr.vdis[self.uuid] = self
def delete(self) -> None:
"Physically delete the VDI"
lock.Lock.cleanup(self.uuid, NS_PREFIX_LVM + self.sr.uuid)
lock.Lock.cleanupAll(self.uuid)
self._clear()
def getParent(self) -> str:
return self.cowutil.getParent(self.path, lambda x: x.strip())
def repair(self, parent) -> None:
self.cowutil.repair(parent)
@override
def __str__(self) -> str:
strHidden = ""
if self.isHidden():
strHidden = "*"
strSizeVirt = "?"
if self.sizeVirt > 0:
strSizeVirt = Util.num2str(self.sizeVirt)
strSizePhys = "?"
if self._sizePhys > 0:
strSizePhys = "/%s" % Util.num2str(self._sizePhys)
strSizeAllocated = "?"
if self._sizeAllocated >= 0:
strSizeAllocated = "/%s" % Util.num2str(self._sizeAllocated)
strType = "[{}]".format(self.vdi_type)
return "%s%s(%s%s%s)%s" % (strHidden, self.uuid[0:8], strSizeVirt,
strSizePhys, strSizeAllocated, strType)
def validate(self, fast=False) -> None:
if self.cowutil.check(self.path, fast=fast) != CowUtil.CheckResult.Success:
raise util.SMException("COW image %s corrupted" % self)
def _clear(self):
self.uuid = ""
self.path = ""
self.parentUuid = ""
self.parent = None
self._clearRef()
def _clearRef(self):
self._vdiRef = None
@staticmethod
def _cancel_exception(sig, frame):
raise CancelException()
def _call_plugin_coalesce(self, hostRef, leaf):
signal.signal(signal.SIGTERM, self._cancel_exception)
args = {"path": self.path, "vdi_type": self.vdi_type, "leaf_path": leaf.path}
Util.log("Calling remote coalesce plugin with: {}".format(args))
try:
ret = self.sr.xapi.session.xenapi.host.call_plugin( \
hostRef, XAPI.PLUGIN_ON_SLAVE, "commit_tapdisk", args)
Util.log("Remote coalesce returned {}".format(ret))
except CancelException:
Util.log(f"Cancelling online coalesce following signal {args}")
self.sr.xapi.session.xenapi.host.call_plugin( \
hostRef, XAPI.PLUGIN_ON_SLAVE, "commit_cancel", args)
raise
except Exception:
raise
def _doCoalesceOnHost(self, hostRef, leaf):
self.parent._increaseSizeVirt(self.sizeVirt)
self.sr._updateSlavesOnResize(self.parent)
self._coalesceCowImageOnHost(hostRef, leaf)
#self._verifyContents(0)
self.parent.updateBlockInfo()
def _isOpenOnHosts(self) -> Optional[str]:
for pbdRecord in self.sr.xapi.getAttachedPBDs():
hostRef = pbdRecord["host"]
args = {"path": self.path}
is_openers = util.strtobool(self.sr.xapi.session.xenapi.host.call_plugin( \
hostRef, XAPI.PLUGIN_ON_SLAVE, "is_openers", args))
if is_openers:
return hostRef
return None
def _doCoalesce(self) -> None:
"""Coalesce self onto parent. Only perform the actual coalescing of
an image, but not the subsequent relinking. We'll do that as the next step,
after reloading the entire SR in case things have changed while we
were coalescing"""
self.validate()
self.parent.validate(True)
self.parent._increaseSizeVirt(self.sizeVirt)
self.sr._updateSlavesOnResize(self.parent)
self._coalesceCowImage(0)
self.parent.validate(True)
#self._verifyContents(0)
self.parent.updateBlockInfo()
def _verifyContents(self, timeOut):
Util.log(" Coalesce verification on %s" % self)
abortTest = lambda: IPCFlag(self.sr.uuid).test(FLAG_TYPE_ABORT)
Util.runAbortable(lambda: self._runTapdiskDiff(), True,
self.sr.uuid, abortTest, VDI.POLL_INTERVAL, timeOut)
Util.log(" Coalesce verification succeeded")
def _runTapdiskDiff(self):
cmd = "tapdisk-diff -n %s:%s -m %s:%s" % \
(self.getDriverName(), self.path, \
self.parent.getDriverName(), self.parent.path)
Util.doexec(cmd, 0)
return True
@staticmethod
def _reportCoalesceError(vdi, ce):
"""Reports a coalesce error to XenCenter.
vdi: the VDI object on which the coalesce error occured
ce: the CommandException that was raised"""
msg_name = os.strerror(ce.code)
if ce.code == errno.ENOSPC:
# TODO We could add more information here, e.g. exactly how much
# space is required for the particular coalesce, as well as actions
# to be taken by the user and consequences of not taking these
# actions.
msg_body = 'Run out of space while coalescing.'
elif ce.code == errno.EIO:
msg_body = 'I/O error while coalescing.'
else:
msg_body = ''
util.SMlog('Coalesce failed on SR %s: %s (%s)'
% (vdi.sr.uuid, msg_name, msg_body))
# Create a XenCenter message, but don't spam.
xapi = vdi.sr.xapi.session.xenapi
sr_ref = xapi.SR.get_by_uuid(vdi.sr.uuid)
oth_cfg = xapi.SR.get_other_config(sr_ref)
if COALESCE_ERR_RATE_TAG in oth_cfg:
coalesce_err_rate = float(oth_cfg[COALESCE_ERR_RATE_TAG])
else:
coalesce_err_rate = DEFAULT_COALESCE_ERR_RATE
xcmsg = False
if coalesce_err_rate == 0:
xcmsg = True
elif coalesce_err_rate > 0:
now = datetime.datetime.now()
sm_cfg = xapi.SR.get_sm_config(sr_ref)
if COALESCE_LAST_ERR_TAG in sm_cfg:
# seconds per message (minimum distance in time between two
# messages in seconds)
spm = datetime.timedelta(seconds=(1.0 / coalesce_err_rate) * 60)
last = datetime.datetime.fromtimestamp(
float(sm_cfg[COALESCE_LAST_ERR_TAG]))
if now - last >= spm:
xapi.SR.remove_from_sm_config(sr_ref,
COALESCE_LAST_ERR_TAG)
xcmsg = True
else:
xcmsg = True
if xcmsg:
xapi.SR.add_to_sm_config(sr_ref, COALESCE_LAST_ERR_TAG,
str(now.strftime('%s')))
if xcmsg:
xapi.message.create(msg_name, "3", "SR", vdi.sr.uuid, msg_body)
def coalesce(self) -> int:
return self.cowutil.coalesce(self.path)
@staticmethod
def _doCoalesceCowImage(vdi: "VDI"):
try:
startTime = time.time()
allocated_size = vdi.getAllocatedSize()
coalesced_size = vdi.coalesce()
endTime = time.time()
vdi.sr.recordStorageSpeed(startTime, endTime, coalesced_size)
except util.CommandException as ce:
# We use try/except for the following piece of code because it runs
# in a separate process context and errors will not be caught and
# reported by anyone.
try:
# Report coalesce errors back to user via XC
VDI._reportCoalesceError(vdi, ce)
except Exception as e:
util.SMlog('failed to create XenCenter message: %s' % e)
raise ce
except:
raise
def _vdi_is_raw(self, vdi_path):
"""
Given path to vdi determine if it is raw
"""
uuid = self.extractUuid(vdi_path)
return self.sr.vdis[uuid].vdi_type == VdiType.RAW
def _coalesceCowImage(self, timeOut):
Util.log(" Running COW coalesce on %s" % self)
def abortTest():
if self.cowutil.isCoalesceableOnRemote():
file = self.sr._gc_running_file(self)
try: