forked from xapi-project/sm
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtest_cleanup.py
More file actions
2013 lines (1613 loc) · 73 KB
/
Copy pathtest_cleanup.py
File metadata and controls
2013 lines (1613 loc) · 73 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
from sm_typing import Dict, List, override
import errno
import signal
import unittest
import unittest.mock as mock
import uuid
from uuid import uuid4
import cleanup
import fjournaler
import lock
import util
import vhdutil
import ipc
import XenAPI
from XenAPI import Failure
from util import SMException
MEGA = 1024 * 1024
class FakeFile(object):
pass
class FakeException(Exception):
pass
class FakeUtil:
record: List[str] = []
def log(input):
FakeUtil.record.append(input)
log = staticmethod(log)
class AlwaysLockedLock(object):
def acquireNoblock(self):
return False
class AlwaysFreeLock(object):
def acquireNoblock(self):
return True
class TestRelease(object):
def acquireNoblock(self):
return True
class IrrelevantLock(object):
pass
def create_cleanup_sr(xapi, uuid=None):
return cleanup.SR(uuid=uuid, xapi=xapi, createLock=False, force=False)
class TestSR(unittest.TestCase):
@override
def setUp(self) -> None:
time_sleep_patcher = mock.patch('cleanup.time.sleep')
self.mock_time_sleep = time_sleep_patcher.start()
updateBlockInfo_patcher = mock.patch('cleanup.VDI.updateBlockInfo')
self.mock_updateBlockInfo = updateBlockInfo_patcher.start()
IPCflag_patcher = mock.patch('cleanup.IPCFlag')
self.mock_IPCFlag = IPCflag_patcher.start()
blktap2_patcher = mock.patch('cleanup.blktap2', autospec=True)
self.mock_blktap2 = blktap2_patcher.start()
self.xapi_mock = mock.MagicMock(name='MockXapi')
self.xapi_mock.srRecord = {'name_label': 'dummy'}
self.xapi_mock.isPluggedHere.return_value = True
self.xapi_mock.isMaster.return_value = True
self.mock_xapi_session = mock.MagicMock(name="MockSession")
self.xapi_mock.getSession.return_value = self.mock_xapi_session
self.addCleanup(mock.patch.stopall)
@override
def tearDown(self) -> None:
cleanup.SIGTERM = False
def setup_abort_flag(self, ipc_mock, should_abort=False):
flag = mock.Mock()
flag.test = mock.Mock(return_value=should_abort)
ipc_mock.return_value = flag
def setup_mock_sr(self, mock_sr):
mock_sr.configure_mock(uuid=1234, xapi=self.xapi_mock,
createLock=False, force=False)
def mock_cleanup_locks(self):
cleanup.lockGCActive = TestRelease()
cleanup.lockGCActive.release = mock.Mock(return_value=None)
cleanup.lockGCRunning = TestRelease()
cleanup.lockGCRunning.release = mock.Mock(return_value=None)
def test_check_no_space_candidates_none(self):
sr = create_cleanup_sr(self.xapi_mock)
sr.xapi.srRecord.update({
"sm_config": {}
})
sr.check_no_space_candidates()
self.mock_xapi_session.xenapi.message.create.assert_not_called()
def test_check_no_space_candidates_one_not_reported(self):
sr = create_cleanup_sr(self.xapi_mock)
vdi_uuid = str(uuid.uuid4())
mock_vdi = mock.MagicMock()
mock_vdi.uuid = vdi_uuid
sr.no_space_candidates = {
vdi_uuid: mock_vdi
}
sr.xapi.srRecord.update({
"sm_config": {}
})
self.mock_xapi_session.xenapi.VDI.get_other_config.return_value = {}
xapi_message = self.mock_xapi_session.xenapi.message
xapi_message.get_record.side_effect = XenAPI.Failure(
details='No such message')
sr.check_no_space_candidates()
self.mock_xapi_session.xenapi.message.create.assert_called_once_with(
'SM_GC_NO_SPACE', 3, 'SR', sr.uuid,
"Unable to perform data coalesce "
f"due to a lack of space in SR {sr.uuid}")
def test_check_no_space_candidates_one_already_reported(self):
sr = create_cleanup_sr(self.xapi_mock)
vdi_uuid = str(uuid.uuid4())
mock_vdi = mock.MagicMock()
mock_vdi.uuid = vdi_uuid
sr.no_space_candidates = {
vdi_uuid: mock_vdi
}
sr.xapi.srRecord.update({
"sm_config": {"gc_no_space": "dummy ref"}
})
self.mock_xapi_session.xenapi.VDI.get_other_config.return_value = {}
self.mock_xapi_session.xenapi.message.get_record.side_effect = {
'name': 'SM_GC_NO_SPACE'
}
sr.check_no_space_candidates()
self.mock_xapi_session.xenapi.message.create.assert_not_called()
def test_check_no_space_candidates_none_clear_message(self):
sr = create_cleanup_sr(self.xapi_mock)
vdi_uuid = str(uuid.uuid4())
mock_vdi = mock.MagicMock()
mock_vdi.uuid = vdi_uuid
sr.no_space_candidates = {}
sr.xapi.srRecord.update({
"sm_config": {"gc_no_space": "dummy ref"}
})
self.mock_xapi_session.xenapi.VDI.get_other_config.return_value = {}
self.mock_xapi_session.xenapi.message.get_record.side_effect = {
'name': 'SM_GC_NO_SPACE'
}
sr.check_no_space_candidates()
self.mock_xapi_session.xenapi.message.destroy.assert_called_once_with(
"dummy ref"
)
def test_term_handler(self):
self.assertFalse(cleanup.SIGTERM)
cleanup.receiveSignal(signal.SIGTERM, None)
self.assertTrue(cleanup.SIGTERM)
@mock.patch('cleanup._create_init_file', autospec=True)
@mock.patch('cleanup.SR', autospec=True)
def test_loop_exits_on_term(self, mock_init, mock_sr):
# Set the term signel
cleanup.receiveSignal(signal.SIGTERM, None)
mock_session = mock.MagicMock(name='MockSession')
sr_uuid = str(uuid4())
self.mock_cleanup_locks()
# Trigger GC
cleanup.gc(mock_session, sr_uuid, inBackground=False)
def test_lock_if_already_locked(self):
"""
Given an already locked SR, a lock call
increments the lock counter
"""
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = IrrelevantLock()
sr._locked = 1
sr.lock()
self.assertEqual(2, sr._locked)
def test_lock_if_no_locking_is_used(self):
"""
Given no srLock present, the lock operations don't touch
the counter
"""
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = None
sr.lock()
self.assertEqual(0, sr._locked)
def test_lock_succeeds_if_lock_is_acquired(self):
"""
After performing a lock, the counter equals to 1
"""
self.setup_abort_flag(self.mock_IPCFlag)
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = AlwaysFreeLock()
sr.lock()
self.assertEqual(1, sr._locked)
def test_lock_raises_exception_if_abort_requested(self):
"""
If IPC abort was requested, lock raises AbortException
"""
self.setup_abort_flag(self.mock_IPCFlag, should_abort=True)
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = AlwaysLockedLock()
self.assertRaises(cleanup.AbortException, sr.lock)
def test_lock_raises_exception_if_unable_to_acquire_lock(self):
"""
If the lock is busy, SMException is raised
"""
self.setup_abort_flag(self.mock_IPCFlag)
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = AlwaysLockedLock()
self.assertRaises(util.SMException, sr.lock)
def test_lock_leaves_sr_consistent_if_unable_to_acquire_lock(self):
"""
If the lock is busy, the lock counter is not incremented
"""
self.setup_abort_flag(self.mock_IPCFlag)
sr = create_cleanup_sr(self.xapi_mock)
sr._srLock = AlwaysLockedLock()
with self.assertRaises(util.SMException):
sr.lock()
self.assertEqual(0, sr._locked)
def test_gcPause_fist_point_legal(self):
"""
Make sure the fist point has been added to the array of legal
fist points.
"""
self.assertTrue(util.fistpoint.is_legal(util.GCPAUSE_FISTPOINT))
@mock.patch('util.fistpoint', autospec=True)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup.Util.runAbortable')
def test_gcPause_calls_fist_point(
self,
mock_abortable,
mock_sr,
mock_fist):
"""
Call fist point if active and not abortable sleep.
"""
self.setup_mock_sr(mock_sr)
# Fake that we have an active fist point.
mock_fist.is_active.return_value = True
cleanup._gcLoopPause(mock_sr, False)
# Make sure we check for correct fist point.
mock_fist.is_active.assert_called_with(util.GCPAUSE_FISTPOINT)
# Make sure we are calling the fist point.
mock_fist.activate_custom_fn.assert_called_with(util.GCPAUSE_FISTPOINT,
mock.ANY)
# And don't call abortable sleep
mock_abortable.assert_not_called()
@mock.patch('util.fistpoint', autospec=True)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup.Util.runAbortable')
@mock.patch('os.path.exists', autospec=True)
def test_gcPause_calls_abortable_sleep(
self,
mock_exists,
mock_abortable,
mock_sr,
mock_fist_point):
"""
Call abortable sleep if fist point is not active.
"""
self.setup_mock_sr(mock_sr)
# Fake that the fist point is not active.
mock_fist_point.is_active.return_value = False
# The GC init file does exist
mock_exists.return_value = True
cleanup._gcLoopPause(mock_sr, False)
# Make sure we check for the active fist point.
mock_fist_point.is_active.assert_called_with(util.GCPAUSE_FISTPOINT)
# Fist point is not active so call abortable sleep.
mock_abortable.assert_called_with(mock.ANY, None, mock_sr.uuid,
mock.ANY, cleanup.VDI.POLL_INTERVAL,
cleanup.GCPAUSE_DEFAULT_SLEEP * 1.1)
@mock.patch('util.fistpoint', autospec=True)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup.Util.runAbortable')
@mock.patch('os.path.exists', autospec=True)
def test_gcPause_skipped_on_first_run(
self,
mock_exists,
mock_abortable,
mock_sr,
mock_fist_point):
"""
Don't sleep the GC on the first run after host boot.
"""
self.setup_mock_sr(mock_sr)
# Fake that the fist point is not active.
mock_fist_point.is_active.return_value = False
# The GC init file doesn't exist
mock_exists.return_value = False
cleanup._gcLoopPause(mock_sr, False)
# Make sure we check for the active fist point.
mock_fist_point.is_active.assert_called_with(util.GCPAUSE_FISTPOINT)
# Fist point is not active so call abortable sleep.
self.assertEqual(0, mock_abortable.call_count)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup.Util.runAbortable')
def test_gc_pause_skipped_if_immediate(self, mock_abortable, mock_sr):
"""
Foreground GC runs immediate
"""
## Arrange
self.setup_mock_sr(mock_sr)
## Act
cleanup._gcLoopPause(mock_sr, False, immediate=True)
## Assert
# Never call runAbortable
self.assertEqual(0, mock_abortable.call_count)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup._abort')
def test_lock_released_by_abort_when_held(
self,
mock_abort,
mock_sr):
"""
If _abort returns True make sure we release the lockGCActive which will
have been held by _abort, also check that we return True.
"""
self.setup_mock_sr(mock_sr)
# Fake that abort returns True, so we hold lockGCActive.
mock_abort.return_value = True
# Setup mock of release function.
cleanup.lockGCActive = TestRelease()
cleanup.lockGCActive.release = mock.Mock(return_value=None)
ret = cleanup.abort(str(mock_sr.uuid), False)
# Pass on the return from _abort.
self.assertEqual(True, ret)
# We hold lockGCActive so make sure we release it.
self.assertEqual(cleanup.lockGCActive.release.call_count, 1)
@mock.patch('cleanup.SR', autospec=True)
@mock.patch('cleanup._abort')
def test_lock_not_released_by_abort_when_not_held(
self,
mock_abort,
mock_sr):
"""
If _abort returns False don't release lockGCActive and ensure that
False returned by _abort is passed on.
"""
self.setup_mock_sr(mock_sr)
# Fake _abort returning False.
mock_abort.return_value = False
# Mock lock release function.
cleanup.lockGCActive = TestRelease()
cleanup.lockGCActive.release = mock.Mock(return_value=None)
ret = cleanup.abort(mock_sr, False)
# Make sure pass on False returned by _abort
self.assertEqual(False, ret)
# Make sure we did not release the lock as we don't have it.
self.assertEqual(cleanup.lockGCActive.release.call_count, 0)
@mock.patch('cleanup._abort')
@mock.patch('cleanup.input')
def test_abort_optional_renable_active_held(
self,
mock_input,
mock_abort):
"""
Cli has option to re enable gc make sure we release the locks
correctly if _abort returns True.
"""
mock_abort.return_value = True
mock_input.return_value = None
self.mock_cleanup_locks()
cleanup.abort_optional_reenable(None)
# Make sure released lockGCActive
self.assertEqual(cleanup.lockGCActive.release.call_count, 1)
# Make sure released lockRunning
self.assertEqual(cleanup.lockGCRunning.release.call_count, 1)
@mock.patch('cleanup._abort')
@mock.patch('cleanup.input')
def test_abort_optional_renable_active_not_held(
self,
mock_input,
mock_abort):
"""
Cli has option to reenable gc make sure we release the locks
correctly if _abort return False.
"""
mock_abort.return_value = False
mock_input.return_value = None
self.mock_cleanup_locks()
cleanup.abort_optional_reenable(None)
# Don't release lockGCActive, we don't hold it.
self.assertEqual(cleanup.lockGCActive.release.call_count, 0)
# Make sure released lockRunning
self.assertEqual(cleanup.lockGCRunning.release.call_count, 1)
@mock.patch('cleanup.init')
def test__abort_returns_true_when_get_lock(
self,
mock_init):
"""
_abort should return True when it can get
the lockGCActive straight off the bat.
"""
cleanup.lockGCActive = AlwaysFreeLock()
ret = cleanup._abort(None)
self.assertEqual(ret, True)
@mock.patch('cleanup.init')
def test__abort_return_false_if_flag_not_set(
self,
mock_init):
"""
If flag not set return False.
"""
mock_init.return_value = None
# Fake the flag returning False.
self.mock_IPCFlag.return_value.set.return_value = False
# Not important for this test but we call it so mock it.
cleanup.lockGCActive = AlwaysLockedLock()
ret = cleanup._abort(None)
self.assertEqual(self.mock_IPCFlag.return_value.set.call_count, 1)
self.assertEqual(ret, False)
@mock.patch('cleanup.init')
def test__abort_should_raise_if_cant_get_lock(self, mock_init):
"""
_abort should raise an exception if it completely
fails to get lockGCActive.
"""
mock_init.return_value = None
# Fake return true so we don't bomb out straight away.
self.mock_IPCFlag.return_value.set.return_value = True
# Fake never getting the lock.
cleanup.lockGCActive = AlwaysLockedLock()
with self.assertRaises(util.CommandException):
cleanup._abort(None)
@mock.patch('cleanup.init')
def test__abort_should_succeed_if_aquires_on_second_attempt(
self,
mock_init
):
"""
_abort should succeed if gets lock on second attempt
"""
mock_init.return_value = None
# Fake return true so we don't bomb out straight away.
self.mock_IPCFlag.return_value.set.return_value = True
# Use side effect to fake failing to get the lock
# on the first call, succeeding on the second.
mocked_lock = AlwaysLockedLock()
mocked_lock.acquireNoblock = mock.Mock()
mocked_lock.acquireNoblock.side_effect = [False, True]
cleanup.lockGCActive = mocked_lock
ret = cleanup._abort(None)
self.assertEqual(mocked_lock.acquireNoblock.call_count, 2)
self.assertEqual(ret, True)
@mock.patch('cleanup.init')
def test__abort_should_fail_if_reaches_maximum_retries_for_lock(
self,
mock_init
):
"""
_abort should fail if we max out the number of attempts for
obtaining the lock.
"""
mock_init.return_value = None
# Fake return true so we don't bomb out straight away.
self.mock_IPCFlag.return_value.set.return_value = True
# Fake a series of failed attempts to get the lock.
mocked_lock = AlwaysLockedLock()
mocked_lock.acquireNoblock = mock.Mock()
# +1 to SR.LOCK_RETRY_ATTEMPTS as we attempt to get lock
# once outside the loop.
side_effect = [False] * (cleanup.SR.LOCK_RETRY_ATTEMPTS + 1)
# Make sure we are not trying once again
side_effect.append(True)
mocked_lock.acquireNoblock.side_effect = side_effect
cleanup.lockGCActive = mocked_lock
# We've failed repeatedly to gain the lock so raise exception.
with self.assertRaises(util.CommandException) as te:
cleanup._abort(None)
the_exception = te.exception
self.assertIsNotNone(the_exception)
self.assertEqual(errno.ETIMEDOUT, the_exception.code)
self.assertEqual(mocked_lock.acquireNoblock.call_count,
cleanup.SR.LOCK_RETRY_ATTEMPTS + 1)
@mock.patch('cleanup.init')
def test__abort_succeeds_if_gets_lock_on_final_attempt(self, mock_init):
"""
_abort succeeds if we get the lockGCActive on the final retry
"""
mock_init.return_value = None
self.mock_IPCFlag.return_value.set.return_value = True
mocked_lock = AlwaysLockedLock()
mocked_lock.acquireNoblock = mock.Mock()
# +1 to SR.LOCK_RETRY_ATTEMPTS as we attempt to get lock
# once outside the loop.
side_effect = [False] * (cleanup.SR.LOCK_RETRY_ATTEMPTS)
# On the final attempt we succeed.
side_effect.append(True)
mocked_lock.acquireNoblock.side_effect = side_effect
cleanup.lockGCActive = mocked_lock
ret = cleanup._abort(None)
self.assertEqual(mocked_lock.acquireNoblock.call_count,
cleanup.SR.LOCK_RETRY_ATTEMPTS + 1)
self.assertEqual(ret, True)
@mock.patch('cleanup.lock', autospec=True)
def test_file_vdi_delete(self, mock_lock):
"""
Test to confirm fix for HFX-651
"""
mock_lock.Lock = mock.MagicMock(spec=lock.Lock)
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
vdi.delete()
mock_lock.Lock.cleanupAll.assert_called_with(str(vdi_uuid))
@mock.patch('cleanup.VDI', autospec=True)
@mock.patch('cleanup.SR._liveLeafCoalesce', autospec=True)
@mock.patch('cleanup.SR._snapshotCoalesce', autospec=True)
def test_coalesceLeaf(self, mock_srSnapshotCoalesce,
mock_srLeafCoalesce, mock_vdi):
mock_vdi.canLiveCoalesce.return_value = True
mock_srLeafCoalesce.return_value = "This is a test"
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
res = sr._coalesceLeaf(vdi)
self.assertEqual(res, "This is a test")
self.assertEqual(sr._liveLeafCoalesce.call_count, 1)
self.assertEqual(sr._snapshotCoalesce.call_count, 0)
@mock.patch('cleanup.VDI', autospec=True)
@mock.patch('cleanup.SR._liveLeafCoalesce', autospec=True)
@mock.patch('cleanup.SR._snapshotCoalesce', autospec=True)
def test_coalesceLeaf_coalesce_failed(self,
mock_srSnapshotCoalesce,
mock_srLeafCoalesce,
mock_vdi):
mock_vdi.canLiveCoalesce.return_value = False
mock_srSnapshotCoalesce.return_value = False
mock_srLeafCoalesce.return_value = False
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
res = sr._coalesceLeaf(vdi)
self.assertFalse(res)
@mock.patch('cleanup.VDI.canLiveCoalesce', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.getSizeVHD', autospec=True)
@mock.patch('cleanup.SR._snapshotCoalesce', autospec=True,
return_value=True)
@mock.patch('cleanup.Util.log')
def test_coalesceLeaf_size_bigger(self, mock_log,
mock_snapshotCoalesce, mock_vhdSize,
mock_vdiLiveCoalesce):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
mock_vhdSize.side_effect = iter([1024, 4096, 4096, 8000, 8000, 16000])
sr._snapshotCoalesce = mock.MagicMock(autospec=True)
sr._snapshotCoalesce.return_value = True
with self.assertRaises(util.SMException) as exc:
sr._coalesceLeaf(vdi)
self.assertIn("VDI {uuid} could not be"
" coalesced".format(uuid=vdi_uuid),
str(exc.exception))
@mock.patch('cleanup.VDI.canLiveCoalesce', autospec=True)
@mock.patch('cleanup.VDI.getSizeVHD', autospec=True)
@mock.patch('cleanup.SR._snapshotCoalesce', autospec=True,
return_value=True)
@mock.patch('cleanup.SR._liveLeafCoalesce', autospec=True,
return_value="This is a Test")
@mock.patch('cleanup.Util.log')
def test_coalesceLeaf_success_after_4_iterations(self,
mock_log,
mock_liveLeafCoalesce,
mock_snapshotCoalesce,
mock_vhdSize,
mock_vdiLiveCoalesce):
mock_vdiLiveCoalesce.side_effect = iter([False, False, False, True])
mock_snapshotCoalesce.side_effect = iter([True, True, True])
mock_vhdSize.side_effect = iter([1024, 1023, 1023, 1022, 1022, 1021])
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
res = sr._coalesceLeaf(vdi)
self.assertEqual(res, "This is a Test")
self.assertEqual(4, mock_vdiLiveCoalesce.call_count)
self.assertEqual(3, mock_snapshotCoalesce.call_count)
self.assertEqual(6, mock_vhdSize.call_count)
@mock.patch('cleanup.Util.log')
def test_findLeafCoalesceable_forbidden1(self, mock_log):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
sr.xapi.srRecord = {"other_config": {cleanup.VDI.DB_COALESCE: "false"}}
res = sr.findLeafCoalesceable()
self.assertEqual(res, [])
mock_log.assert_called_with("Coalesce disabled for this SR")
@mock.patch('cleanup.Util.log')
def test_findLeafCoalesceable_forbidden2(self, mock_log):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
sr.xapi.srRecord = \
{"other_config":
{cleanup.VDI.DB_LEAFCLSC: cleanup.VDI.LEAFCLSC_DISABLED}}
res = sr.findLeafCoalesceable()
self.assertEqual(res, [])
mock_log.assert_called_with("Leaf-coalesce disabled for this SR")
@mock.patch('cleanup.Util.log')
def test_findLeafCoalesceable_forbidden3(self, mock_log):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
sr.xapi.srRecord = {"other_config":
{cleanup.VDI.DB_LEAFCLSC:
cleanup.VDI.LEAFCLSC_DISABLED,
cleanup.VDI.DB_COALESCE:
"false"}}
res = sr.findLeafCoalesceable()
self.assertEqual(res, [])
mock_log.assert_called_with("Coalesce disabled for this SR")
@mock.patch('cleanup.Util.log')
def test_findLeafCoalesceable_forbidden4(self, mock_log):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
sr.xapi.srRecord = {"other_config": {cleanup.VDI.DB_LEAFCLSC:
cleanup.VDI.LEAFCLSC_DISABLED,
cleanup.VDI.DB_COALESCE:
"true"}}
res = sr.findLeafCoalesceable()
self.assertEqual(res, [])
mock_log.assert_called_with("Leaf-coalesce disabled for this SR")
@mock.patch('cleanup.Util.log')
def test_findLeafCoalesceable_forbidden5(self, mock_log):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
sr.xapi.srRecord = {"other_config": {cleanup.VDI.DB_LEAFCLSC:
cleanup.VDI.LEAFCLSC_FORCE,
cleanup.VDI.DB_COALESCE:
"false"}}
res = sr.findLeafCoalesceable()
self.assertEqual(res, [])
mock_log.assert_called_with("Coalesce disabled for this SR")
# Utils for testing gatherLeafCoalesceable.
def srWithOneGoodVDI(self, mock_getConfig, goodConfig):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
vdi_uuid = uuid4()
if goodConfig:
mock_getConfig.side_effect = goodConfig
else:
mock_getConfig.side_effect = iter(["good", False, "blah", "blah"])
good = cleanup.VDI(sr, str(vdi_uuid), False)
sr.vdis = {"good": good}
return sr, good
def addBadVDITOSR(self, sr, config, coalesceable=True):
vdi_uuid = uuid4()
bad = cleanup.VDI(sr, str(vdi_uuid), False)
bad.getConfig = mock.MagicMock(side_effect=iter(config))
bad.isLeafCoalesceable = mock.MagicMock(return_value=coalesceable)
sr.vdis.update({"bad": bad})
return bad
def gather_candidates(self, mock_getConfig, config, coalesceable=True,
failed=False, expected=None, goodConfig=None):
sr, good = self.srWithOneGoodVDI(mock_getConfig, goodConfig)
bad = self.addBadVDITOSR(sr, config, coalesceable=coalesceable)
if failed:
sr._failedCoalesceTargets = [bad]
res = []
sr.gatherLeafCoalesceable(res)
self.assertEqual(res, [good])
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", True)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_leaf_not_coalescable(self, mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden
):
""" The bad vdi returns false for isLeafCoalesceable and is not
added to the list.
"""
self.gather_candidates(mock_getConfig,
iter(["blah", False, "blah", "blah"]),
coalesceable=False)
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", True)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_failed_candidates(self,
mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden):
""" The bad vdi is in the failed list so is not added to the list."""
self.gather_candidates(mock_getConfig, iter(["blah", False, "blah",
"blah"]), failed=True)
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", True)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_reset(self, mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden):
"""bad has cleanup.VDI.ONBOOT_RESET so not added to list"""
self.gather_candidates(mock_getConfig,
iter([cleanup.VDI.ONBOOT_RESET, False, "blah",
"blah"]))
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", True)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_caching_allowed(self, mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden):
"""Bad candidate has caching allowed so not added"""
self.gather_candidates(mock_getConfig, iter(["blah", True, "blah",
"blah"]))
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", True)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_clsc_disabled(self, mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden):
"""clsc disabled so not added"""
self.gather_candidates(mock_getConfig,
iter(["blah", False,
cleanup.VDI.LEAFCLSC_DISABLED,
"blah"]))
@mock.patch("cleanup.AUTO_ONLINE_LEAF_COALESCE_ENABLED", False)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.VDI.isLeafCoalesceable', autospec=True,
return_value=True)
@mock.patch('cleanup.VDI.getConfig', autospec=True)
def test_gather_candidates_auto_coalesce_off(self, mock_getConfig,
mock_isLeafCoalesceable,
mock_leafCoalesceForbidden):
"""Globally turned off but good vdi has force"""
self.gather_candidates(mock_getConfig,
iter(["blah", False, "blah", "blah"]),
goodConfig=iter(["blah", False, "blah",
cleanup.VDI.LEAFCLSC_FORCE]))
def makeVDIReturningSize(self, sr, size, canLiveCoalesce, liveSize):
vdi_uuid = uuid4()
vdi = cleanup.VDI(sr, str(vdi_uuid), False)
vdi._calcExtraSpaceForSnapshotCoalescing = \
mock.MagicMock(return_value=size)
vdi.canLiveCoalesce = mock.MagicMock(return_value=canLiveCoalesce)
vdi._calcExtraSpaceForLeafCoalescing = \
mock.MagicMock(return_value=liveSize)
vdi.setConfig = mock.MagicMock()
return vdi
def findLeafCoalesceable(self, mock_gatherLeafCoalesceable, goodSize,
canLiveCoalesce=False, liveSize=None,
expectedNothing=False):
sr_uuid = uuid4()
sr = create_cleanup_sr(self.xapi_mock, uuid=str(sr_uuid))
good = self.makeVDIReturningSize(sr, goodSize, canLiveCoalesce,
liveSize)
bad = self.makeVDIReturningSize(sr, 4096, False, 4096)
def fakeCandidates(blah, stuff):
stuff.append(good)
stuff.append(bad)
mock_gatherLeafCoalesceable.side_effect = fakeCandidates
res = sr.findLeafCoalesceable()
if expectedNothing:
self.assertEqual(res, None)
else:
self.assertEqual(res, good)
return good, bad
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.SR.getFreeSpace', autospec=True, return_value=1024)
@mock.patch('cleanup.SR.gatherLeafCoalesceable', autospec=True)
def test_insufficient_space(self, mock_gatherLeafCoalesceable,
mock_getFreeSpace,
mock_leafCoalesceForbidden):
"""Good vdi calculates space less than remaining on sr"""
self.findLeafCoalesceable(mock_gatherLeafCoalesceable, 4)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.SR.getFreeSpace', autospec=True, return_value=1024)
@mock.patch('cleanup.SR.gatherLeafCoalesceable', autospec=True)
def test_space_equal(self, mock_gatherLeafCoalesceable,
mock_getFreeSpace,
mock_leafCoalesceForbidden):
"""Good has calculates space equal to remaining space"""
self.findLeafCoalesceable(mock_gatherLeafCoalesceable, 1024)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.SR.getFreeSpace', autospec=True, return_value=1024)
@mock.patch('cleanup.SR.gatherLeafCoalesceable', autospec=True)
def test_fall_back_to_leaf_coalescing(self, mock_gatherLeafCoalesceable,
mock_getFreeSpace,
mock_leafCoalesceForbidden):
"""Good VDI can can live coalesce and has right size"""
self.findLeafCoalesceable(mock_gatherLeafCoalesceable, 4096,
canLiveCoalesce=True,
liveSize=4)
@mock.patch('cleanup.SR.leafCoalesceForbidden', autospec=True,
return_value=False)
@mock.patch('cleanup.SR.getFreeSpace', autospec=True, return_value=1024)
@mock.patch('cleanup.SR.gatherLeafCoalesceable', autospec=True)
def test_leaf_coalescing_cannt_live_coalesce(self,
mock_gatherLeafCoalesceable,
mock_getFreeSpace,
mock_leafCoalesceForbidden):
"""1st VDI is too big for snap but right size for live
2nd VDI is too big for snap and too big for live"""
vdi1, vdi2 = self.findLeafCoalesceable(mock_gatherLeafCoalesceable,
4097,