This repository was archived by the owner on Sep 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTestSupervisor.hs
1471 lines (1312 loc) · 58.5 KB
/
TestSupervisor.hs
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
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE Rank2Types #-}
-- NOTICE: Some of these tests are /unsafe/, and will fail intermittently, since
-- they rely on ordering constraints which the Cloud Haskell runtime does not
-- guarantee.
module Main where
import Control.Concurrent.MVar
( MVar
, newMVar
, putMVar
, takeMVar
)
import qualified Control.Exception as Ex
import Control.Exception (throwIO)
import Control.Distributed.Process hiding (call, monitor, finally)
import Control.Distributed.Process.Closure
import Control.Distributed.Process.Node
import Control.Distributed.Process.Extras.Internal.Types
import Control.Distributed.Process.Extras.Internal.Primitives
import Control.Distributed.Process.Extras.SystemLog
( LogLevel(Debug)
, systemLogFile
, addFormatter
, debug
, logChannel
)
import Control.Distributed.Process.Extras.Time
import Control.Distributed.Process.Extras.Timer
import Control.Distributed.Process.Supervisor hiding (start, shutdown)
import qualified Control.Distributed.Process.Supervisor as Supervisor
import Control.Distributed.Process.Supervisor.Management
( MxSupervisor(..)
, monitorSupervisor
, unmonitorSupervisor
, supervisionMonitor
)
import Control.Distributed.Process.ManagedProcess.Client (shutdown)
import Control.Distributed.Process.Serializable()
import Control.Distributed.Static (staticLabel)
import Control.Monad (void, unless, forM_, forM)
import Control.Monad.Catch (finally)
import Control.Rematch
( equalTo
, is
, isNot
, isNothing
, isJust
)
import Data.ByteString.Lazy (empty)
import Data.Maybe (catMaybes)
#if !MIN_VERSION_base(4,6,0)
import Prelude hiding (catch)
#endif
import Test.HUnit (Assertion, assertFailure)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import TestUtils hiding (waitForExit)
import qualified Network.Transport as NT
import System.Random (mkStdGen, randomR)
-- test utilities
expectedExitReason :: ProcessId -> String
expectedExitReason sup = "killed-by=" ++ (show sup) ++
",reason=StoppedBySupervisor"
defaultWorker :: ChildStart -> ChildSpec
defaultWorker clj =
ChildSpec
{
childKey = ""
, childType = Worker
, childRestart = Temporary
, childRestartDelay = Nothing
, childStop = StopImmediately
, childStart = clj
, childRegName = Nothing
}
tempWorker :: ChildStart -> ChildSpec
tempWorker clj =
(defaultWorker clj)
{
childKey = "temp-worker"
, childRestart = Temporary
}
transientWorker :: ChildStart -> ChildSpec
transientWorker clj =
(defaultWorker clj)
{
childKey = "transient-worker"
, childRestart = Transient
}
intrinsicWorker :: ChildStart -> ChildSpec
intrinsicWorker clj =
(defaultWorker clj)
{
childKey = "intrinsic-worker"
, childRestart = Intrinsic
}
permChild :: ChildStart -> ChildSpec
permChild clj =
(defaultWorker clj)
{
childKey = "perm-child"
, childRestart = Permanent
}
ensureProcessIsAlive :: ProcessId -> Process ()
ensureProcessIsAlive pid = do
result <- isProcessAlive pid
expectThat result $ is True
runInTestContext :: LocalNode
-> MVar ()
-> ShutdownMode
-> RestartStrategy
-> [ChildSpec]
-> (ProcessId -> Process ())
-> Assertion
runInTestContext node lock sm rs cs proc = do
Ex.bracket (takeMVar lock) (putMVar lock) $ \() -> runProcess node $ do
sup <- Supervisor.start rs sm cs
(proc sup) `finally` (exit sup ExitShutdown)
data Context = Context { sup :: SupervisorPid
, sniffer :: Sniffer
, waitTimeout :: TimeInterval
, listSize :: Int
, split :: forall a . ([a] -> ([a], [a]))
}
type Sniffer = ReceivePort MxSupervisor
mkRandom :: Int -> Int -> (Int, Int)
mkRandom minListSz maxListSz
| minListSz > maxListSz = error "nope"
| minListSz < 20 = mkRandom 20 maxListSz
| otherwise =
let gen = mkStdGen 273846
(lSz :: Int, gen') = randomR (minListSz, maxListSz) gen
(sPt :: Int, _) = randomR (max 3 (round((fromIntegral lSz) / 3.15 :: Double) :: Int), lSz - 3) gen'
in (lSz, sPt)
randomIshSizes :: (Int, Int)
randomIshSizes = mkRandom 20 1200
runInTestContext' :: LocalNode
-> ShutdownMode
-> RestartStrategy
-> [ChildSpec]
-> (Context -> Process ())
-> Assertion
runInTestContext' node sm rs cs proc = do
liftIO $ do
-- we don't care about real randomness, just about selecting a vaguely
-- different sizes for each run...
let (lSz, sPt) = randomIshSizes
runProcess node $ do
sup <- Supervisor.start rs sm cs
sf <- monitorSupervisor sup
finally (proc $ Context sup sf (seconds 30) lSz (splitAt sPt))
(exit sup ExitShutdown >> unmonitorSupervisor sup)
verifyChildWasRestarted :: ChildKey -> ProcessId -> ProcessId -> Process ()
verifyChildWasRestarted key pid sup = do
void $ waitForExit pid
cSpec <- lookupChild sup key
-- TODO: handle (ChildRestarting _) too!
case cSpec of
Just (ref, _) -> do Just pid' <- resolve ref
expectThat pid' $ isNot $ equalTo pid
_ -> do
liftIO $ assertFailure $ "unexpected child ref: " ++ (show (key, cSpec))
verifyChildWasNotRestarted :: ChildKey -> ProcessId -> ProcessId -> Process ()
verifyChildWasNotRestarted key pid sup = do
void $ waitForExit pid
cSpec <- lookupChild sup key
case cSpec of
Just (ChildStopped, _) -> return ()
_ -> liftIO $ assertFailure $ "unexpected child ref: " ++ (show (key, cSpec))
verifyTempChildWasRemoved :: ProcessId -> ProcessId -> Process ()
verifyTempChildWasRemoved pid sup = do
void $ waitForExit pid
sleepFor 500 Millis
cSpec <- lookupChild sup "temp-worker"
expectThat cSpec isNothing
waitForExit :: ProcessId -> Process DiedReason
waitForExit pid = do
monitor pid >>= waitForDown
waitForDown :: Maybe MonitorRef -> Process DiedReason
waitForDown Nothing = error "invalid mref"
waitForDown (Just ref) =
receiveWait [ matchIf (\(ProcessMonitorNotification ref' _ _) -> ref == ref')
(\(ProcessMonitorNotification _ _ dr) -> return dr) ]
waitForBranchRestartComplete :: Sniffer
-> ChildKey
-> Process ()
waitForBranchRestartComplete sniff key = do
debug logChannel $ "waiting for branch restart..."
aux 10000 sniff Nothing -- `finally` unmonitorSupervisor sup
where
aux :: Int -> Sniffer -> Maybe MxSupervisor -> Process ()
aux n s m
| n < 1 = liftIO $ assertFailure $ "Never Saw Branch Restarted for " ++ (show key)
| Just mx <- m
, SupervisorBranchRestarted{..} <- mx
, childSpecKey == key = return ()
| Nothing <- m = receiveTimeout 100 [ matchChan s return ] >>= aux (n-1) s
| otherwise = aux (n-1) s Nothing
verifySingleRestart :: Context
-> ChildKey
-> Process ()
verifySingleRestart Context{..} key = do
sleep $ seconds 1
let t = asTimeout waitTimeout
mx <- receiveChanTimeout t sniffer
case mx of
Just rs@SupervisedChildRestarting{} -> do
(childSpecKey rs) `shouldBe` equalTo key
mx' <- receiveChanTimeout t sniffer
case mx' of
Just cs@SupervisedChildStarted{} -> do
(childSpecKey cs) `shouldBe` equalTo key
debug logChannel $ "restart ok for " ++ (show cs)
_ -> liftIO $ assertFailure $ " Unexpected Waiting Child Started " ++ (show mx')
_ -> liftIO $ assertFailure $ "Unexpected Waiting Child Restarted " ++ (show mx)
verifySeqStartOrder :: Context
-> [(ChildRef, Child)]
-> ChildKey
-> Process ()
verifySeqStartOrder Context{..} xs toStop = do
-- xs == [(oldRef, (ref, spec))] in specified/insertion order
-- if shutdown is LeftToRight then that's correct, otherwise we
-- should expect the shutdowns in reverse order
sleep $ seconds 1
let t = asTimeout waitTimeout
forM_ xs $ \(oCr, c@(cr, cs)) -> do
debug logChannel $ "checking restart " ++ (show c)
mx <- receiveTimeout t [ matchChan sniffer return ]
case mx of
Just SupervisedChildRestarting{..} -> do
debug logChannel $ "for restart " ++ (show childSpecKey) ++ " we're expecting " ++ (childKey cs)
childSpecKey `shouldBe` equalTo (childKey cs)
unless (childSpecKey == toStop) $ do
Just SupervisedChildStopped{..} <- receiveChanTimeout t sniffer
debug logChannel $ "for " ++ (show childRef) ++ " we're expecting " ++ (show oCr)
childRef `shouldBe` equalTo oCr
mx' <- receiveChanTimeout t sniffer
case mx' of
Just SupervisedChildStarted{..} -> childRef `shouldBe` equalTo cr
_ -> do
liftIO $ assertFailure $ "After Stopping " ++ (show cs) ++
" received unexpected " ++ (show mx)
_ -> liftIO $ assertFailure $ "Bad Restart: " ++ (show mx)
verifyStopStartOrder :: Context
-> [(ChildRef, Child)]
-> [Child]
-> ChildKey
-> Process ()
verifyStopStartOrder Context{..} xs restarted toStop = do
-- xs == [(oldRef, (ref, spec))] in specified/insertion order
-- if shutdown is LeftToRight then that's correct, otherwise we
-- should expect the shutdowns in reverse order
sleep $ seconds 1
let t = asTimeout waitTimeout
forM_ xs $ \(oCr, c@(_, cs)) -> do
debug logChannel $ "checking restart " ++ (show c)
mx <- receiveTimeout t [ matchChan sniffer return ]
case mx of
Just SupervisedChildRestarting{..} -> do
debug logChannel $ "for restart " ++ (show childSpecKey) ++ " we're expecting " ++ (childKey cs)
childSpecKey `shouldBe` equalTo (childKey cs)
if childSpecKey /= toStop
then do Just SupervisedChildStopped{..} <- receiveChanTimeout t sniffer
debug logChannel $ "for " ++ (show childRef) ++ " we're expecting " ++ (show oCr)
-- childRef `shouldBe` equalTo oCr
if childRef /= oCr
then debug logChannel $ "childRef " ++ (show childRef) ++ " /= " ++ (show oCr)
else return ()
else return ()
_ -> liftIO $ assertFailure $ "Bad Restart: " ++ (show mx)
debug logChannel "checking start order..."
sleep $ seconds 1
forM_ restarted $ \(cr, _) -> do
debug logChannel $ "checking (reverse) start order for " ++ (show cr)
mx <- receiveTimeout t [ matchChan sniffer return ]
case mx of
Just SupervisedChildStarted{..} -> childRef `shouldBe` equalTo cr
_ -> liftIO $ assertFailure $ "Bad Child Start: " ++ (show mx)
checkStartupOrder :: Context -> [Child] -> Process ()
checkStartupOrder Context{..} children = do
-- assert that we saw the startup sequence working...
forM_ children $ \(cr, _) -> do
debug logChannel $ "checking " ++ (show cr)
mx <- receiveTimeout (asTimeout waitTimeout) [ matchChan sniffer return ]
case mx of
Just SupervisedChildStarted{..} -> childRef `shouldBe` equalTo cr
_ -> liftIO $ assertFailure $ "Bad Child Start: " ++ (show mx)
exitIgnore :: Process ()
exitIgnore = liftIO $ throwIO ChildInitIgnore
noOp :: Process ()
noOp = return ()
blockIndefinitely :: Process ()
blockIndefinitely = runTestProcess noOp
notifyMe :: ProcessId -> Process ()
notifyMe me = getSelfPid >>= send me >> obedient
sleepy :: Process ()
sleepy = (sleepFor 5 Minutes)
`catchExit` (\_ (_ :: ExitReason) -> return ()) >> sleepy
obedient :: Process ()
obedient = (sleepFor 5 Minutes)
{- supervisor inserts handlers that act like we wrote:
`catchExit` (\_ (r :: ExitReason) -> do
case r of
ExitShutdown -> return ()
_ -> die r)
-}
runCore :: SendPort () -> Process ()
runCore sp = (expect >>= say) `catchExit` (\_ ExitShutdown -> sendChan sp ())
runApp :: SendPort () -> Process ()
runApp sg = do
Just pid <- whereis "core"
link pid -- if the real "core" exits first, we go too
sendChan sg ()
expect >>= say
formatMxSupervisor :: Message -> Process (Maybe String)
formatMxSupervisor msg = do
m <- unwrapMessage msg :: Process (Maybe MxSupervisor)
case m of
Nothing -> return Nothing
Just m' -> return $ Just (show m')
$(remotable [ 'exitIgnore
, 'noOp
, 'blockIndefinitely
, 'sleepy
, 'obedient
, 'notifyMe
, 'runCore
, 'runApp
, 'formatMxSupervisor ])
-- test cases start here...
normalStartStop :: ProcessId -> Process ()
normalStartStop sup = do
ensureProcessIsAlive sup
void $ monitor sup
shutdown sup
sup `shouldExitWith` DiedNormal
sequentialShutdown :: TestResult (Maybe ()) -> Process ()
sequentialShutdown result = do
(sp, rp) <- newChan
(sg, rg) <- newChan
core' <- toChildStart $ $(mkClosure 'runCore) sp
app' <- toChildStart $ $(mkClosure 'runApp) sg
let core = (permChild core') { childRegName = Just (LocalName "core")
, childStop = StopTimeout (Delay $ within 2 Seconds)
, childKey = "child-1"
}
let app = (permChild app') { childRegName = Just (LocalName "app")
, childStop = StopTimeout (Delay $ within 2 Seconds)
, childKey = "child-2"
}
sup <- Supervisor.start restartRight
(SequentialShutdown RightToLeft)
[core, app]
() <- receiveChan rg
exit sup ExitShutdown
res <- receiveChanTimeout (asTimeout $ seconds 5) rp
stash result res
configuredTemporaryChildExitsWithIgnore ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
configuredTemporaryChildExitsWithIgnore cs withSupervisor =
let spec = tempWorker cs in do
withSupervisor restartOne [spec] verifyExit
where
verifyExit :: ProcessId -> Process ()
verifyExit sup = do
child <- lookupChild sup "temp-worker"
case child of
Nothing -> return () -- the child exited and was removed ok
Just (ref, _) -> do
Just pid <- resolve ref
verifyTempChildWasRemoved pid sup
configuredNonTemporaryChildExitsWithIgnore ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
configuredNonTemporaryChildExitsWithIgnore cs withSupervisor =
let spec = transientWorker cs in do
withSupervisor restartOne [spec] $ verifyExit spec
where
verifyExit :: ChildSpec -> ProcessId -> Process ()
verifyExit spec sup = do
sleep $ milliSeconds 100 -- make sure our super has seen the EXIT signal
child <- lookupChild sup (childKey spec)
case child of
Nothing -> liftIO $ assertFailure $ "lost non-temp spec!"
Just (ref, spec') -> do
rRef <- resolve ref
maybe (return DiedNormal) waitForExit rRef
cSpec <- lookupChild sup (childKey spec')
case cSpec of
Just (ChildStartIgnored, _) -> return ()
_ -> do
liftIO $ assertFailure $ "unexpected lookup: " ++ (show cSpec)
startTemporaryChildExitsWithIgnore :: ChildStart -> ProcessId -> Process ()
startTemporaryChildExitsWithIgnore cs sup =
-- if a temporary child exits with "ignore" then we must
-- have deleted its specification from the supervisor
let spec = tempWorker cs in do
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
verifyTempChildWasRemoved pid sup
startNonTemporaryChildExitsWithIgnore :: ChildStart -> ProcessId -> Process ()
startNonTemporaryChildExitsWithIgnore cs sup =
let spec = transientWorker cs in do
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
void $ waitForExit pid
sleep $ milliSeconds 250
cSpec <- lookupChild sup (childKey spec)
case cSpec of
Just (ChildStartIgnored, _) -> return ()
_ -> do
liftIO $ assertFailure $ "unexpected lookup: " ++ (show cSpec)
addChildWithoutRestart :: ChildStart -> ProcessId -> Process ()
addChildWithoutRestart cs sup =
let spec = transientWorker cs in do
response <- addChild sup spec
response `shouldBe` equalTo (ChildAdded ChildStopped)
addChildThenStart :: ChildStart -> ProcessId -> Process ()
addChildThenStart cs sup =
let spec = transientWorker cs in do
(ChildAdded _) <- addChild sup spec
response <- startChild sup (childKey spec)
case response of
ChildStartOk (ChildRunning pid) -> do
alive <- isProcessAlive pid
alive `shouldBe` equalTo True
_ -> do
liftIO $ putStrLn (show response)
die "Ooops"
startUnknownChild :: ChildStart -> ProcessId -> Process ()
startUnknownChild cs sup = do
response <- startChild sup (childKey (transientWorker cs))
response `shouldBe` equalTo ChildStartUnknownId
setupChild :: ChildStart -> ProcessId -> Process (ChildRef, ChildSpec)
setupChild cs sup = do
let spec = transientWorker cs
response <- addChild sup spec
response `shouldBe` equalTo (ChildAdded ChildStopped)
Just child <- lookupChild sup "transient-worker"
return child
addDuplicateChild :: ChildStart -> ProcessId -> Process ()
addDuplicateChild cs sup = do
(ref, spec) <- setupChild cs sup
dup <- addChild sup spec
dup `shouldBe` equalTo (ChildFailedToStart $ StartFailureDuplicateChild ref)
startDuplicateChild :: ChildStart -> ProcessId -> Process ()
startDuplicateChild cs sup = do
(ref, spec) <- setupChild cs sup
dup <- startNewChild sup spec
dup `shouldBe` equalTo (ChildFailedToStart $ StartFailureDuplicateChild ref)
startBadClosure :: ChildStart -> ProcessId -> Process ()
startBadClosure cs sup = do
let spec = tempWorker cs
child <- startNewChild sup spec
child `shouldBe` equalTo
(ChildFailedToStart $ StartFailureBadClosure
"user error (Could not resolve closure: Invalid static label 'non-existing')")
-- configuredBadClosure withSupervisor = do
-- let spec = permChild (closure (staticLabel "non-existing") empty)
-- -- we make sure we don't hit the supervisor's limits
-- let strategy = RestartOne $ limit (maxRestarts 500000000) (milliSeconds 1)
-- withSupervisor strategy [spec] $ \sup -> do
-- -- ref <- monitor sup
-- children <- (listChildren sup)
-- let specs = map fst children
-- expectThat specs $ equalTo []
deleteExistingChild :: ChildStart -> ProcessId -> Process ()
deleteExistingChild cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
result <- deleteChild sup "transient-worker"
result `shouldBe` equalTo (ChildNotStopped ref)
deleteStoppedTempChild :: ChildStart -> ProcessId -> Process ()
deleteStoppedTempChild cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
-- child needs to be stopped
waitForExit pid
result <- deleteChild sup (childKey spec)
result `shouldBe` equalTo ChildNotFound
deleteStoppedChild :: ChildStart -> ProcessId -> Process ()
deleteStoppedChild cs sup = do
let spec = transientWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
-- child needs to be stopped
waitForExit pid
result <- deleteChild sup (childKey spec)
result `shouldBe` equalTo ChildDeleted
permanentChildrenAlwaysRestart :: ChildStart -> ProcessId -> Process ()
permanentChildrenAlwaysRestart cs sup = do
let spec = permChild cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid -- a normal stop should *still* trigger a restart
verifyChildWasRestarted (childKey spec) pid sup
temporaryChildrenNeverRestart :: ChildStart -> ProcessId -> Process ()
temporaryChildrenNeverRestart cs sup = do
let spec = tempWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyTempChildWasRemoved pid sup
transientChildrenNormalExit :: ChildStart -> ProcessId -> Process ()
transientChildrenNormalExit cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
verifyChildWasNotRestarted (childKey spec) pid sup
transientChildrenAbnormalExit :: ChildStart -> ProcessId -> Process ()
transientChildrenAbnormalExit cs sup = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyChildWasRestarted (childKey spec) pid sup
transientChildrenExitShutdown :: ChildStart -> Context -> Process ()
transientChildrenExitShutdown cs Context{..} = do
let spec = transientWorker cs
(ChildAdded ref) <- startNewChild sup spec
Just _ <- receiveChanTimeout (asTimeout waitTimeout) sniffer :: Process (Maybe MxSupervisor)
Just pid <- resolve ref
mRef <- monitor pid
exit pid ExitShutdown
waitForDown mRef
mx <- receiveChanTimeout 1000 sniffer :: Process (Maybe MxSupervisor)
expectThat mx isNothing
verifyChildWasNotRestarted (childKey spec) pid sup
intrinsicChildrenAbnormalExit :: ChildStart -> ProcessId -> Process ()
intrinsicChildrenAbnormalExit cs sup = do
let spec = intrinsicWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
kill pid "bye bye"
verifyChildWasRestarted (childKey spec) pid sup
intrinsicChildrenNormalExit :: ChildStart -> ProcessId -> Process ()
intrinsicChildrenNormalExit cs sup = do
let spec = intrinsicWorker cs
ChildAdded ref <- startNewChild sup spec
Just pid <- resolve ref
testProcessStop pid
reason <- waitForExit sup
expectThat reason $ equalTo DiedNormal
explicitRestartRunningChild :: ChildStart -> ProcessId -> Process ()
explicitRestartRunningChild cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
result <- restartChild sup (childKey spec)
expectThat result $ equalTo $ ChildRestartFailed (StartFailureAlreadyRunning ref)
explicitRestartUnknownChild :: ProcessId -> Process ()
explicitRestartUnknownChild sup = do
result <- restartChild sup "unknown-id"
expectThat result $ equalTo ChildRestartUnknownId
explicitRestartRestartingChild :: ChildStart -> ProcessId -> Process ()
explicitRestartRestartingChild cs sup = do
let spec = permChild cs
ChildAdded _ <- startNewChild sup spec
-- TODO: we've seen a few explosions here (presumably of the supervisor?)
-- expecially when running with +RTS -N1 - it's possible that there's a bug
-- tucked away that we haven't cracked just yet
restarted <- (restartChild sup (childKey spec))
`catchExit` (\_ (r :: ExitReason) -> (liftIO $ putStrLn (show r)) >>
die r)
-- this is highly timing dependent, so we have to allow for both
-- possible outcomes - on a dual core machine, the first clause
-- will match approx. 1 / 200 times when running with +RTS -N
case restarted of
ChildRestartFailed (StartFailureAlreadyRunning (ChildRestarting _)) -> return ()
ChildRestartFailed (StartFailureAlreadyRunning (ChildRunning _)) -> return ()
other -> liftIO $ assertFailure $ "unexpected result: " ++ (show other)
explicitRestartStoppedChild :: ChildStart -> ProcessId -> Process ()
explicitRestartStoppedChild cs sup = do
let spec = transientWorker cs
let key = childKey spec
ChildAdded ref <- startNewChild sup spec
void $ stopChild sup key
restarted <- restartChild sup key
sleepFor 500 Millis
Just (ref', _) <- lookupChild sup key
expectThat ref $ isNot $ equalTo ref'
case restarted of
ChildRestartOk (ChildRunning _) -> return ()
_ -> liftIO $ assertFailure $ "unexpected exit: " ++ (show restarted)
stopChildImmediately :: ChildStart -> ProcessId -> Process ()
stopChildImmediately cs sup = do
let spec = tempWorker cs
ChildAdded ref <- startNewChild sup spec
-- Just pid <- resolve ref
mRef <- monitor ref
void $ stopChild sup (childKey spec)
reason <- waitForDown mRef
expectThat reason $ equalTo $ DiedException (expectedExitReason sup)
stoppingChildExceedsDelay :: ProcessId -> Process ()
stoppingChildExceedsDelay sup = do
let spec = (tempWorker (RunClosure $(mkStaticClosure 'sleepy)))
{ childStop = StopTimeout (Delay $ within 500 Millis) }
ChildAdded ref <- startNewChild sup spec
-- Just pid <- resolve ref
mRef <- monitor ref
void $ stopChild sup (childKey spec)
reason <- waitForDown mRef
expectThat reason $ equalTo $ DiedException (expectedExitReason sup)
stoppingChildObeysDelay :: ProcessId -> Process ()
stoppingChildObeysDelay sup = do
let spec = (tempWorker (RunClosure $(mkStaticClosure 'obedient)))
{ childStop = StopTimeout (Delay $ within 1 Seconds) }
ChildAdded child <- startNewChild sup spec
Just pid <- resolve child
void $ monitor pid
void $ stopChild sup (childKey spec)
child `shouldExitWith` DiedNormal
restartAfterThreeAttempts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartAfterThreeAttempts cs withSupervisor = do
let spec = permChild cs
let strategy = RestartOne $ limit (maxRestarts 500) (seconds 2)
withSupervisor strategy [spec] $ \sup -> do
mapM_ (\_ -> do
[(childRef, _)] <- listChildren sup
Just pid <- resolve childRef
ref <- monitor pid
testProcessStop pid
void $ waitForDown ref) [1..3 :: Int]
[(_, _)] <- listChildren sup
return ()
delayedRestartAfterThreeAttempts ::
(RestartStrategy -> [ChildSpec] -> (Context -> Process ()) -> Assertion)
-> Assertion
delayedRestartAfterThreeAttempts withSupervisor = do
let spec = (permChild $ RunClosure $ $(mkStaticClosure 'blockIndefinitely))
{ childRestartDelay = Just (seconds 3) }
let strategy = RestartOne $ limit (maxRestarts 2) (seconds 2)
withSupervisor strategy [spec] $ \ctx@Context{..} -> do
mapM_ (\_ -> do
[(childRef, _)] <- listChildren sup
Just pid <- resolve childRef
ref <- monitor pid
testProcessStop pid
void $ waitForDown ref) [1..3 :: Int]
Just (ref, _) <- lookupChild sup $ childKey spec
case ref of
ChildRestarting _ -> do
SupervisedChildStarted{..} <- receiveChan sniffer
childSpecKey `shouldBe` equalTo (childKey spec)
_ -> liftIO $ assertFailure $ "Unexpected ChildRef: " ++ (show ref)
mapM_ (const $ verifySingleRestart ctx (childKey spec)) [1..3 :: Int]
[(ref', _)] <- listChildren sup
Just pid <- resolve ref'
mRef <- monitor pid
testProcessStop pid
void $ waitForDown mRef
permanentChildExceedsRestartsIntensity ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
permanentChildExceedsRestartsIntensity cs withSupervisor = do
let spec = permChild cs -- child that exits immediately
let strategy = RestartOne $ limit (maxRestarts 50) (seconds 2)
withSupervisor strategy [spec] $ \sup -> do
ref <- monitor sup
-- if the supervisor dies whilst the call is in-flight,
-- *this* process will exit, therefore we handle that exit reason
void $ ((startNewChild sup spec >> return ())
`catchExit` (\_ (_ :: ExitReason) -> return ()))
reason <- waitForDown ref
expectThat reason $ equalTo $
DiedException $ "exit-from=" ++ (show sup) ++
",reason=ReachedMaxRestartIntensity"
stopChildIgnoresSiblings ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
stopChildIgnoresSiblings cs withSupervisor = do
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..3 :: Int]]
withSupervisor restartAll specs $ \sup -> do
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
mRef <- monitor ref
stopChild sup toStop
waitForDown mRef
children <- listChildren sup
forM_ (tail $ map fst children) $ \cRef -> do
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve cRef
restartAllWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (Context -> Process ()) -> Assertion)
-> Assertion
restartAllWithLeftToRightSeqRestarts cs withSupervisor = do
let (sz, _) = randomIshSizes
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..sz :: Int]]
withSupervisor restartAll specs $ \Context{..} -> do
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
children <- listChildren sup
Just pid <- resolve ref
kill pid "goodbye"
forM_ (map fst children) $ \cRef -> monitor cRef >>= waitForDown
forM_ (map snd children) $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
restartLeftWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (Context -> Process ()) -> Assertion)
-> Assertion
restartLeftWithLeftToRightSeqRestarts cs withSupervisor = do
let (lSz, sptSz) = randomIshSizes
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..lSz :: Int]]
withSupervisor restartLeft specs $ \ctx@Context{..} -> do
children <- listChildren sup
checkStartupOrder ctx children
sniff <- monitorSupervisor sup
let (toRestart, _notToRestart) = splitAt sptSz specs
let (restarts, survivors) = splitAt sptSz children
let toStop = childKey $ last toRestart
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
kill pid "goodbye"
forM_ (map fst restarts) $ \cRef -> monitor cRef >>= waitForDown
-- NB: this uses a separate channel to consume the Mx events...
waitForBranchRestartComplete sniff toStop
children' <- listChildren sup
let (restarted', _) = splitAt sptSz children'
let xs = zip [fst o | o <- restarts] restarted'
verifySeqStartOrder ctx xs toStop
forM_ (map snd children') $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
resolved <- forM (map fst survivors) resolve
let possibleBadRestarts = catMaybes resolved
r <- receiveTimeout (after 5 Seconds) [
match (\(ProcessMonitorNotification _ pid' _) -> do
case (elem pid' possibleBadRestarts) of
True -> liftIO $ assertFailure $ "unexpected exit from " ++ show pid'
False -> return ())
]
expectThat r isNothing
restartRightWithLeftToRightSeqRestarts ::
ChildStart
-> (RestartStrategy -> [ChildSpec] -> (ProcessId -> Process ()) -> Assertion)
-> Assertion
restartRightWithLeftToRightSeqRestarts cs withSupervisor = do
let (lSz, sptSz) = mkRandom 150 688
let templ = permChild cs
let specs = [templ { childKey = (show i) } | i <- [1..lSz :: Int]]
withSupervisor restartRight specs $ \sup -> do
let (_notToRestart, toRestart) = splitAt sptSz specs
let toStop = childKey $ head toRestart
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
children <- listChildren sup
let (survivors, children') = splitAt sptSz children
kill pid "goodbye"
forM_ (map fst children') $ \cRef -> do
mRef <- monitor cRef
waitForDown mRef
forM_ (map snd children') $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
resolved <- forM (map fst survivors) resolve
let possibleBadRestarts = catMaybes resolved
r <- receiveTimeout (after 1 Seconds) [
match (\(ProcessMonitorNotification _ pid' _) -> do
case (elem pid' possibleBadRestarts) of
True -> liftIO $ assertFailure $ "unexpected exit from " ++ show pid'
False -> return ())
]
expectThat r isNothing
restartAllWithLeftToRightRestarts :: ProcessId -> Process ()
restartAllWithLeftToRightRestarts sup = do
let (lSz, _) = randomIshSizes
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..lSz :: Int]]
-- add the specs one by one
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
children <- listChildren sup
drainAllChildren children
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
kill pid "goodbye"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst children) $ \cRef -> do
Just mRef <- monitor cRef
receiveWait [
matchIf (\(ProcessMonitorNotification ref' _ _) -> ref' == mRef)
(\_ -> return ())
-- we should NOT see *any* process signalling that it has started
-- whilst waiting for all the children to be terminated
, match (\(pid' :: ProcessId) -> do
liftIO $ assertFailure $ "unexpected signal from " ++ (show pid'))
]
-- Now assert that all the children were restarted in the same order.
-- THIS is the bit that is technically unsafe, though it's also unlikely
-- to change, since the architecture of the node controller is pivotal to CH
children' <- listChildren sup
drainAllChildren children'
let [c1, c2] = [map fst cs | cs <- [children, children']]
forM_ (zip c1 c2) $ \(p1, p2) -> expectThat p1 $ isNot $ equalTo p2
where
drainAllChildren children = do
-- Receive all pids then verify they arrived in the correct order.
-- Any out-of-order messages (such as ProcessMonitorNotification) will
-- violate the invariant asserted below, and fail the test case
pids <- forM children $ \_ -> expect :: Process ProcessId
forM_ pids ensureProcessIsAlive
restartAllWithRightToLeftSeqRestarts :: Context -> Process ()
restartAllWithRightToLeftSeqRestarts ctx@Context{..} = do
self <- getSelfPid
let templ = permChild $ RunClosure $(mkStaticClosure 'obedient)
let specs = [templ { childKey = (show i) } | i <- [1..listSize :: Int]]
-- add the specs one by one
forM_ specs $ \s -> do
ChildAdded ref <- startNewChild sup s
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref
-- assert that we saw the startup sequence working...
children <- listChildren sup
checkStartupOrder ctx children
-- we need this before the restarts occur
sniff <- monitorSupervisor sup
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
kill pid "fooboo"
-- wait for all the exit signals, so we know the children are restarting
forM_ (map fst children) $ \cRef -> monitor cRef >>= waitForDown
-- NB: this uses a separate channel to consume the Mx events...
waitForBranchRestartComplete sniff toStop
children' <- listChildren sup
let xs = zip [fst o | o <- children] children'
verifySeqStartOrder ctx (reverse xs) toStop
forM_ (map snd children') $ \cSpec -> do
Just (ref', _) <- lookupChild sup (childKey cSpec)
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref'
expectLeftToRightRestarts :: Context -> Process ()
expectLeftToRightRestarts ctx@Context{..} = do
let templ = permChild $ RunClosure $(mkStaticClosure 'obedient)
let specs = [templ { childKey = (show i) } | i <- [1..listSize :: Int]]
-- add the specs one by one
forM_ specs $ \s -> void $ startNewChild sup s
-- assert that we saw the startup sequence working...
children <- listChildren sup
checkStartupOrder ctx children
let toStop = childKey $ head specs
Just (ref, _) <- lookupChild sup toStop
Just pid <- resolve ref
-- wait for all the exit signals and ensure they arrive in RightToLeft order
refs <- forM children $ \(ch, _) -> monitor ch >>= \r -> return (ch, r)
kill pid "fooboo"
initRes <- receiveTimeout
(asTimeout $ seconds 1)
[ matchIf
(\(ProcessMonitorNotification r _ _) -> (Just r) == (snd $ head refs))
(\sig@(ProcessMonitorNotification _ _ _) -> return sig) ]
expectThat initRes $ isJust
forM_ (reverse (filter ((/= ref) .fst ) refs)) $ \(_, Just mRef) -> do
(ProcessMonitorNotification ref' _ _) <- expect
if ref' == mRef then (return ()) else (die "unexpected monitor signal")
expectRightToLeftRestarts :: Bool -> Context -> Process ()
expectRightToLeftRestarts rev ctx@Context{..} = do
self <- getSelfPid
let templ = permChild $ RunClosure ($(mkClosure 'notifyMe) self)
let specs = [templ { childKey = (show i) } | i <- [1..listSize :: Int]]
-- add the specs one by one
forM_ specs $ \s -> do
ChildAdded ref <- startNewChild sup s
maybe (error "invalid ref") ensureProcessIsAlive =<< resolve ref
children <- listChildren sup
checkStartupOrder ctx children