-
Notifications
You must be signed in to change notification settings - Fork 210
/
Pools.hs
966 lines (888 loc) · 34.2 KB
/
Pools.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
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
-- |
-- Copyright: © 2020 IOHK
-- License: Apache-2.0
--
-- This module provides tools to collect a consistent view of stake pool data,
-- as provided through @StakePoolLayer@.
module Cardano.Wallet.Shelley.Pools
( StakePoolLayer (..)
, newStakePoolLayer
, monitorStakePools
, monitorMetadata
-- * Logs
, StakePoolLog (..)
)
where
import Prelude
import Cardano.BM.Data.Severity
( Severity (..) )
import Cardano.BM.Data.Tracer
( HasPrivacyAnnotation (..), HasSeverityAnnotation (..) )
import Cardano.Pool.DB
( DBLayer (..), ErrPointAlreadyExists (..), readPoolLifeCycleStatus )
import Cardano.Pool.Metadata
( StakePoolMetadataFetchLog
, defaultManagerSettings
, fetchDelistedPools
, fetchFromRemote
, healthCheck
, identityUrlBuilder
, isHealthy
, newManager
, registryUrlBuilder
)
import Cardano.Wallet
( ErrListPools (..) )
import Cardano.Wallet.Api.Types
( ApiT (..) )
import Cardano.Wallet.Byron.Compatibility
( toByronBlockHeader )
import Cardano.Wallet.Network
( ErrCurrentNodeTip (..)
, ErrNetworkUnavailable (..)
, FollowAction (..)
, FollowExit (..)
, FollowLog
, NetworkLayer (..)
, follow
)
import Cardano.Wallet.Primitive.Slotting
( PastHorizonException (..)
, TimeInterpreter
, epochOf
, firstSlotInEpoch
, startTime
)
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, BlockHeader (..)
, CertificatePublicationTime (..)
, EpochNo (..)
, GenesisParameters (..)
, PoolCertificate (..)
, PoolId
, PoolLifeCycleStatus (..)
, PoolMetadataGCStatus (..)
, PoolMetadataSource (..)
, PoolRegistrationCertificate (..)
, PoolRetirementCertificate (..)
, ProtocolParameters (..)
, Settings (..)
, SlotLength (..)
, SlotNo (..)
, SlottingParameters (..)
, StakePoolMetadata
, StakePoolMetadataHash
, getPoolRegistrationCertificate
, getPoolRetirementCertificate
, unSmashServer
)
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Shelley.Compatibility
( Shelley
, StandardCrypto
, getProducer
, poolCertsFromShelleyBlock
, toCardanoBlockHeader
, toShelleyBlockHeader
)
import Cardano.Wallet.Shelley.Network
( NodePoolLsqData (..) )
import Cardano.Wallet.Unsafe
( unsafeMkPercentage )
import Control.Concurrent
( forkFinally, threadDelay )
import Control.Exception
( AsyncException (..)
, SomeException (..)
, asyncExceptionFromException
, bracket
, finally
, mask_
, try
)
import Control.Monad
( forM, forM_, forever, void, when )
import Control.Monad.IO.Class
( liftIO )
import Control.Monad.Trans.Except
( ExceptT (..), mapExceptT, runExceptT, throwE, withExceptT )
import Control.Monad.Trans.State
( State, evalState, state )
import Control.Retry
( RetryStatus (..), constantDelay, retrying )
import Control.Tracer
( Tracer, contramap, traceWith )
import Data.Bifunctor
( first )
import Data.Function
( (&) )
import Data.Generics.Internal.VL.Lens
( view )
import Data.IORef
( IORef, newIORef, readIORef, writeIORef )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map
( Map )
import Data.Map.Merge.Strict
( dropMissing, traverseMissing, zipWithAMatched, zipWithMatched )
import Data.Maybe
( catMaybes, fromMaybe )
import Data.Ord
( Down (..) )
import Data.Quantity
( Percentage (..), Quantity (..) )
import Data.Set
( Set )
import Data.Text
( Text )
import Data.Text.Class
( ToText (..) )
import Data.Time.Clock.POSIX
( getPOSIXTime, posixDayLength )
import Data.Tuple.Extra
( dupe )
import Data.Word
( Word64 )
import Fmt
( fixedF, pretty )
import GHC.Conc
( TVar, ThreadId, killThread, newTVarIO, readTVarIO, writeTVar )
import GHC.Generics
( Generic )
import Ouroboros.Consensus.Cardano.Block
( CardanoBlock, HardForkBlock (..) )
import System.Random
( RandomGen, random )
import qualified Cardano.Wallet.Api.Types as Api
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Merge.Strict as Map
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified GHC.Conc as STM
--
-- Stake Pool Layer
--
data StakePoolLayer = StakePoolLayer
{ getPoolLifeCycleStatus
:: PoolId
-> IO PoolLifeCycleStatus
, knownPools
:: IO (Set PoolId)
-- | List pools based given the the amount of stake the user intends to
-- delegate, which affects the size of the rewards and the ranking of
-- the pools.
--
-- Pools with a retirement epoch earlier than or equal to the specified
-- epoch will be excluded from the result.
--
, listStakePools
:: EpochNo
-- Exclude all pools that retired in or before this epoch.
-> Coin
-> ExceptT ErrListPools IO [Api.ApiStakePool]
, forceMetadataGC :: IO ()
, putSettings :: Settings -> IO ()
, getSettings :: IO Settings
, getGCMetadataStatus :: IO PoolMetadataGCStatus
}
newStakePoolLayer
:: forall sc. ()
=> TVar PoolMetadataGCStatus
-> NetworkLayer IO (IO Shelley) (CardanoBlock sc)
-> DBLayer IO
-> IO ThreadId
-> IO StakePoolLayer
newStakePoolLayer gcStatus nl db@DBLayer {..} worker = do
tid <- worker
tvTid <- newTVarIO tid
pure $ StakePoolLayer
{ getPoolLifeCycleStatus = _getPoolLifeCycleStatus
, knownPools = _knownPools
, listStakePools = _listPools
, forceMetadataGC = _forceMetadataGC tvTid
, putSettings = _putSettings tvTid
, getSettings = _getSettings
, getGCMetadataStatus = _getGCMetadataStatus
}
where
_getPoolLifeCycleStatus
:: PoolId -> IO PoolLifeCycleStatus
_getPoolLifeCycleStatus pid =
liftIO $ atomically $ readPoolLifeCycleStatus pid
_knownPools
:: IO (Set PoolId)
_knownPools =
Set.fromList <$> liftIO (atomically listRegisteredPools)
-- In order to apply the settings, we have to restart the
-- metadata sync thread as well to avoid race conditions.
_putSettings :: TVar ThreadId -> Settings -> IO ()
_putSettings tvTid settings =
bracketSyncThread tvTid (atomically (gcMetadata >> writeSettings))
where
-- clean up metadata table if the new sync settings suggests so
gcMetadata = do
oldSettings <- readSettings
case (poolMetadataSource oldSettings, poolMetadataSource settings) of
(_, FetchNone) -> -- this is necessary if it's e.g. the first time
-- we start the server with the new feature
-- and the database has still stuff in it
removePoolMetadata
(old, new)
| old /= new -> removePoolMetadata
_ -> pure ()
writeSettings = putSettings settings
_getSettings :: IO Settings
_getSettings = liftIO $ atomically readSettings
_listPools
:: EpochNo
-- Exclude all pools that retired in or before this epoch.
-> Coin
-> ExceptT ErrListPools IO [Api.ApiStakePool]
_listPools currentEpoch userStake = do
tip <- withExceptT fromErrCurrentNodeTip $ currentNodeTip nl
rawLsqData <- mapExceptT (fmap (first ErrListPoolsNetworkError))
$ stakeDistribution nl tip userStake
let lsqData = combineLsqData rawLsqData
dbData <- liftIO $ readPoolDbData db currentEpoch
seed <- liftIO $ atomically readSystemSeed
r <- liftIO $ try $
sortByReward seed
. map snd
. Map.toList
<$> combineDbAndLsqData
(timeInterpreter nl)
(nOpt rawLsqData)
lsqData
dbData
case r of
Left e@(PastHorizon{}) ->
throwE (ErrListPoolsPastHorizonException e)
Right r' -> pure r'
where
fromErrCurrentNodeTip :: ErrCurrentNodeTip -> ErrListPools
fromErrCurrentNodeTip = \case
ErrCurrentNodeTipNetworkUnreachable e ->
ErrListPoolsNetworkError e
ErrCurrentNodeTipNotFound ->
ErrListPoolsNetworkError $ ErrNetworkUnreachable "tip not found"
-- Sort by non-myopic member rewards, making sure to also randomly sort
-- pools that have equal rewards.
--
-- NOTE: we discard the final value of the random generator because we
-- do actually want the order to be stable between two identical
-- requests. The order simply needs to be different between different
-- instances of the server.
sortByReward
:: RandomGen g
=> g
-> [Api.ApiStakePool]
-> [Api.ApiStakePool]
sortByReward g0 =
map stakePool
. L.sortOn (Down . rewards)
. L.sortOn randomWeight
. evalState' g0
. traverse withRandomWeight
where
evalState' :: s -> State s a -> a
evalState' = flip evalState
withRandomWeight :: RandomGen g => a -> State g (Int, a)
withRandomWeight a = do
weight <- state random
pure (weight, a)
rewards = view (#metrics . #nonMyopicMemberRewards) . stakePool
(randomWeight, stakePool) = (fst, snd)
_forceMetadataGC :: TVar ThreadId -> IO ()
_forceMetadataGC tvTid =
-- We force a GC by resetting last sync time to 0 (start of POSIX
-- time) and have the metadata thread restart.
bracketSyncThread tvTid $ do
lastGC <- atomically readLastMetadataGC
case lastGC of
Nothing -> STM.atomically $ writeTVar gcStatus NotStarted
Just gc -> STM.atomically $ writeTVar gcStatus (Restarting gc)
atomically $ putLastMetadataGC $ fromIntegral @Int 0
_getGCMetadataStatus =
readTVarIO gcStatus
-- Stop the sync thread, carry out an action, and restart the sync thread.
bracketSyncThread :: TVar ThreadId -> IO a -> IO ()
bracketSyncThread tvTid action =
void $ bracket
killSyncThread
(\_ -> restartSyncThread)
(\_ -> action)
where
killSyncThread = do
tid <- readTVarIO tvTid
killThread tid
restartSyncThread = do
tid <- worker
STM.atomically $ writeTVar tvTid tid
--
-- Data Combination functions
--
-- | Stake pool-related data that has been read from the node using a local
-- state query.
data PoolLsqData = PoolLsqData
{ nonMyopicMemberRewards :: Quantity "lovelace" Word64
, relativeStake :: Percentage
, saturation :: Double
} deriving (Eq, Show, Generic)
-- | Stake pool-related data that has been read from the database.
data PoolDbData = PoolDbData
{ registrationCert :: PoolRegistrationCertificate
, retirementCert :: Maybe PoolRetirementCertificate
, nProducedBlocks :: Quantity "block" Word64
, metadata :: Maybe StakePoolMetadata
, delisted :: Bool
}
-- | Top level combine-function that merges DB and LSQ data.
combineDbAndLsqData
:: forall m. (Monad m)
=> TimeInterpreter m
-> Int -- ^ nOpt; desired number of pools
-> Map PoolId PoolLsqData
-> Map PoolId PoolDbData
-> m (Map PoolId Api.ApiStakePool)
combineDbAndLsqData ti nOpt lsqData =
Map.mergeA lsqButNoDb dbButNoLsq bothPresent lsqData
where
bothPresent = zipWithAMatched mkApiPool
lsqButNoDb = dropMissing
-- When a pool is registered (with a registration certificate) but not
-- currently active (and therefore not causing pool metrics data to be
-- available over local state query), we use a default value of /zero/
-- for all stake pool metric values so that the pool can still be
-- included in the list of all known stake pools:
--
dbButNoLsq = traverseMissing $ \k db ->
mkApiPool k lsqDefault db
where
lsqDefault = PoolLsqData
{ nonMyopicMemberRewards = freshmanMemberRewards
, relativeStake = minBound
, saturation = 0
}
-- To give a chance to freshly registered pools that haven't been part of
-- any leader schedule, we assign them the average reward of the top @k@
-- pools.
freshmanMemberRewards
= Quantity
$ average
$ L.take nOpt
$ L.sort
$ map (Down . getQuantity . nonMyopicMemberRewards)
$ Map.elems lsqData
where
average [] = 0
average xs = round $ double (sum xs) / double (length xs)
double :: Integral a => a -> Double
double = fromIntegral
mkApiPool
:: PoolId
-> PoolLsqData
-> PoolDbData
-> m Api.ApiStakePool
mkApiPool pid (PoolLsqData prew pstk psat) dbData = do
let mRetirementEpoch = retirementEpoch <$> retirementCert dbData
retirementEpochInfo <- traverse toApiEpochInfo mRetirementEpoch
pure $ Api.ApiStakePool
{ Api.id = (ApiT pid)
, Api.metrics = Api.ApiStakePoolMetrics
{ Api.nonMyopicMemberRewards = fmap fromIntegral prew
, Api.relativeStake = Quantity pstk
, Api.saturation = psat
, Api.producedBlocks =
(fmap fromIntegral . nProducedBlocks) dbData
}
, Api.metadata =
ApiT <$> metadata dbData
, Api.cost =
fmap fromIntegral $ poolCost $ registrationCert dbData
, Api.pledge =
fmap fromIntegral $ poolPledge $ registrationCert dbData
, Api.margin =
Quantity $ poolMargin $ registrationCert dbData
, Api.retirement =
retirementEpochInfo
, Api.flags =
[ Api.Delisted | delisted dbData ]
}
toApiEpochInfo ep = do
time <- ti $ startTime =<< firstSlotInEpoch ep
return $ Api.ApiEpochInfo (ApiT ep) time
-- | Combines all the LSQ data into a single map.
--
-- This is the data we can ask the node for the most recent version of, over the
-- local state query protocol.
--
-- Calculating e.g. the nonMyopicMemberRewards ourselves through chain-following
-- would be completely impractical.
combineLsqData
:: NodePoolLsqData
-> Map PoolId PoolLsqData
combineLsqData NodePoolLsqData{nOpt, rewards, stake} =
Map.merge stakeButNoRewards rewardsButNoStake bothPresent stake rewards
where
-- calculate the saturation from the relative stake
sat s = fromRational $ (getPercentage s) / (1 / fromIntegral nOpt)
-- If we fetch non-myopic member rewards of pools using the wallet
-- balance of 0, the resulting map will be empty. So we set the rewards
-- to 0 here:
stakeButNoRewards = traverseMissing $ \_k s -> pure $ PoolLsqData
{ nonMyopicMemberRewards = Quantity 0
, relativeStake = s
, saturation = (sat s)
}
-- TODO: This case seems possible on shelley_testnet, but why, and how
-- should we treat it?
--
-- The pool with rewards but not stake didn't seem to be retiring.
rewardsButNoStake = traverseMissing $ \_k r -> pure $ PoolLsqData
{ nonMyopicMemberRewards = r
, relativeStake = noStake
, saturation = sat noStake
}
where
noStake = unsafeMkPercentage 0
bothPresent = zipWithMatched $ \_k s r -> PoolLsqData r s (sat s)
-- | Combines all the chain-following data into a single map
combineChainData
:: Map PoolId PoolRegistrationCertificate
-> Map PoolId PoolRetirementCertificate
-> Map PoolId (Quantity "block" Word64)
-> Map StakePoolMetadataHash StakePoolMetadata
-> Set PoolId
-> Map PoolId PoolDbData
combineChainData registrationMap retirementMap prodMap metaMap delistedSet =
Map.map mkPoolDbData $
Map.merge
registeredNoProductions
notRegisteredButProducing
bothPresent
registrationMap
prodMap
where
registeredNoProductions = traverseMissing $ \_k cert ->
pure (cert, Quantity 0)
-- Ignore blocks produced by BFT nodes.
notRegisteredButProducing = dropMissing
bothPresent = zipWithMatched $ const (,)
mkPoolDbData
:: (PoolRegistrationCertificate, Quantity "block" Word64)
-> PoolDbData
mkPoolDbData (registrationCert, n) =
PoolDbData registrationCert mRetirementCert n meta delisted
where
metaHash = snd <$> poolMetadata registrationCert
meta = flip Map.lookup metaMap =<< metaHash
mRetirementCert =
Map.lookup (view #poolId registrationCert) retirementMap
delisted = view #poolId registrationCert `Set.member` delistedSet
readPoolDbData :: DBLayer IO -> EpochNo -> IO (Map PoolId PoolDbData)
readPoolDbData DBLayer {..} currentEpoch = atomically $ do
lifeCycleData <- listPoolLifeCycleData currentEpoch
let registrationCertificates = lifeCycleData
& fmap getPoolRegistrationCertificate
& catMaybes
& fmap (first (view #poolId) . dupe)
& Map.fromList
let retirementCertificates = lifeCycleData
& fmap getPoolRetirementCertificate
& catMaybes
& fmap (first (view #poolId) . dupe)
& Map.fromList
combineChainData
registrationCertificates
retirementCertificates
<$> readTotalProduction
<*> readPoolMetadata
<*> (Set.fromList <$> readDelistedPools)
--
-- Monitoring stake pool
--
monitorStakePools
:: forall t.
Tracer IO StakePoolLog
-> GenesisParameters
-> NetworkLayer IO t (CardanoBlock StandardCrypto)
-> DBLayer IO
-> IO ()
monitorStakePools tr gp nl DBLayer{..} =
monitor =<< mkLatestGarbageCollectionEpochRef
where
monitor latestGarbageCollectionEpochRef = loop
where
loop = do
cursor <- initCursor
traceWith tr $ MsgStartMonitoring cursor
let followTrace = contramap MsgFollow tr
let forwardHandler = forward latestGarbageCollectionEpochRef
follow nl followTrace cursor forwardHandler getHeader >>= \case
FollowInterrupted ->
traceWith tr MsgHaltMonitoring
FollowFailure ->
traceWith tr MsgCrashMonitoring
FollowRollback point -> do
traceWith tr $ MsgRollingBackTo point
liftIO . atomically $ rollbackTo point
loop
GenesisParameters
{ getGenesisBlockHash
, getEpochStability
} = gp
-- In order to prevent the pool database from growing too large over time,
-- we regularly perform garbage collection by removing retired pools from
-- the database.
--
-- However, there is no benefit to be gained from collecting garbage more
-- than once per epoch. In order to avoid invoking the garbage collector
-- too frequently, we keep a reference to the latest epoch for which
-- garbage collection was performed.
--
mkLatestGarbageCollectionEpochRef :: IO (IORef EpochNo)
mkLatestGarbageCollectionEpochRef = newIORef minBound
initCursor :: IO [BlockHeader]
initCursor = atomically $ listHeaders (max 100 k)
where k = fromIntegral $ getQuantity getEpochStability
getHeader :: CardanoBlock StandardCrypto -> BlockHeader
getHeader = toCardanoBlockHeader gp
forward
:: IORef EpochNo
-> NonEmpty (CardanoBlock StandardCrypto)
-> (BlockHeader, ProtocolParameters)
-> IO (FollowAction ())
forward latestGarbageCollectionEpochRef blocks _ = do
atomically $ forAllAndLastM blocks forAllBlocks forLastBlock
pure Continue
where
forAllBlocks = \case
BlockByron _ -> do
pure ()
BlockShelley blk -> do
let (slot, certificates) = poolCertsFromShelleyBlock blk
let header = toShelleyBlockHeader getGenesisBlockHash blk
handleErr (putPoolProduction header (getProducer blk))
garbageCollectPools slot latestGarbageCollectionEpochRef
putPoolCertificates slot certificates
forLastBlock = \case
BlockByron blk ->
putHeader (toByronBlockHeader gp blk)
BlockShelley blk ->
putHeader (toShelleyBlockHeader getGenesisBlockHash blk)
handleErr action = runExceptT action
>>= \case
Left e ->
liftIO $ traceWith tr $ MsgErrProduction e
Right () ->
pure ()
-- | Like 'forM_', except runs the second action for the last element as
-- well (in addition to the first action).
forAllAndLastM :: (Monad m)
=> NonEmpty a
-> (a -> m b) -- ^ action to run for all elements
-> (a -> m c) -- ^ action to run for the last element
-> m ()
{-# INLINE forAllAndLastM #-}
forAllAndLastM ne a1 a2 = go (NE.toList ne)
where
go [] = pure ()
go [x] = a1 x >> a2 x >> go []
go (x:xs) = a1 x >> go xs
-- Perform garbage collection for pools that have retired.
--
-- To avoid any issues with rollback, we err on the side of caution and
-- only garbage collect pools that retired /at least/ two epochs before
-- the current epoch.
--
-- Rationale:
--
-- When crossing an epoch boundary, there is a period of time during which
-- blocks from the previous epoch are still within the rollback window.
--
-- If we've only just crossed the boundary from epoch e into epoch e + 1,
-- this means that blocks from epoch e are still within the rollback
-- window. If the chain we've just been following gets replaced with
-- another chain in which the retirement certificate for some pool p is
-- revoked (with a registration certificate that appears before the end
-- of epoch e), then the retirement for pool p will have been cancelled.
--
-- However, assuming the rollback window is always guaranteed to be less
-- than one epoch in length, retirements that occurred two epochs ago can
-- no longer be affected by rollbacks. Therefore, if we see a retirement
-- that occurred two epochs ago that has not subsquently been superseded,
-- it should be safe to garbage collect that pool.
--
garbageCollectPools currentSlot latestGarbageCollectionEpochRef = do
-- #2196: We need the try. Arguably we shouldn't need it.
liftIO (try @SomeException (timeInterpreter nl (epochOf currentSlot))) >>= \case
Left _ -> return ()
Right currentEpoch | currentEpoch < 2 -> return ()
Right currentEpoch -> do
let latestRetirementEpoch = currentEpoch - 2
latestGarbageCollectionEpoch <-
liftIO $ readIORef latestGarbageCollectionEpochRef
-- Only perform garbage collection once per epoch:
when (latestRetirementEpoch > latestGarbageCollectionEpoch) $ do
liftIO $ do
writeIORef
latestGarbageCollectionEpochRef
latestRetirementEpoch
traceWith tr $
MsgStakePoolGarbageCollection $
PoolGarbageCollectionInfo
{currentEpoch, latestRetirementEpoch}
void $ removeRetiredPools latestRetirementEpoch
-- For each pool certificate in the given list, add an entry to the
-- database that associates the certificate with the specified slot
-- number and the relative position of the certificate in the list.
--
-- The order of certificates within a slot is significant: certificates
-- that appear later take precedence over those that appear earlier on.
--
-- Precedence is determined by the 'readPoolLifeCycleStatus' function.
--
putPoolCertificates slot certificates = do
let publicationTimes =
CertificatePublicationTime slot <$> [minBound ..]
forM_ (publicationTimes `zip` certificates) $ \case
(publicationTime, Registration cert) -> do
liftIO $ traceWith tr $ MsgStakePoolRegistration cert
putPoolRegistration publicationTime cert
(publicationTime, Retirement cert) -> do
liftIO $ traceWith tr $ MsgStakePoolRetirement cert
putPoolRetirement publicationTime cert
-- | Worker thread that monitors pool metadata and syncs it to the database.
monitorMetadata
:: TVar PoolMetadataGCStatus
-> Tracer IO StakePoolLog
-> SlottingParameters
-> DBLayer IO
-> IO ()
monitorMetadata gcStatus tr sp db@(DBLayer{..}) = do
settings <- atomically readSettings
manager <- newManager defaultManagerSettings
healthy <- case poolMetadataSource settings of
FetchSMASH uri -> do
let checkHealth _ = do
r <- healthCheck (Just trFetch) (unSmashServer uri) manager
case r of
(Just health) -> pure $ isHealthy health
_ -> pure False
maxRetries = 8
retryCheck RetryStatus{rsIterNumber} b
| rsIterNumber < maxRetries = pure (not b)
| otherwise = pure False
ms = (* 1_000_000)
baseSleepTime = ms 15
retrying (constantDelay baseSleepTime) retryCheck checkHealth
-- no smash configured, equivalent to healthy
_ -> pure True
if healthy
then do
let fetcher fetchStrategies = fetchFromRemote trFetch fetchStrategies manager
loop getPoolMetadata = forever $ do
(refs, successes) <- getPoolMetadata
when (null refs || null successes) $ do
traceWith tr $ MsgFetchTakeBreak blockFrequency
threadDelay blockFrequency
case poolMetadataSource settings of
FetchNone -> do
STM.atomically $ writeTVar gcStatus NotApplicable
loop (pure ([], [])) -- TODO: exit loop?
FetchDirect -> do
STM.atomically $ writeTVar gcStatus NotApplicable
loop (fetchThem $ fetcher [identityUrlBuilder])
FetchSMASH (unSmashServer -> uri) -> do
STM.atomically $ writeTVar gcStatus NotStarted
let getDelistedPools =
fetchDelistedPools trFetch uri manager
tid <- forkFinally
(gcDelistedPools gcStatus tr db getDelistedPools)
onExit
flip finally (killThread tid) $
loop (fetchThem $ fetcher [registryUrlBuilder uri])
else traceWith tr MsgSMASHUnreachable
where
trFetch = contramap MsgFetchPoolMetadata tr
-- We mask this entire section just in case, although the database
-- operations runs masked anyway. Unfortunately we cannot run
-- @fetchMetadata@ from within atomically, so here we go.
fetchThem fetchMetadata = mask_ $ do
refs <- atomically (unfetchedPoolMetadataRefs 100)
successes <- fmap catMaybes $ forM refs $ \(pid, url, hash) -> do
fetchMetadata pid url hash >>= \case
Nothing -> Nothing <$ do
atomically $ putFetchAttempt (url, hash)
Just meta -> Just hash <$ do
atomically $ putPoolMetadata hash meta
pure (refs, successes)
-- NOTE
-- If there's no metadata, we typically need not to retry sooner than the
-- next block. So waiting for a delay that is roughly the same order of
-- magnitude as the (slot length / active slot coeff) sounds sound.
blockFrequency = ceiling (1/f) * toMicroSecond slotLength
where
toMicroSecond = (`div` 1000000) . fromEnum
slotLength = unSlotLength $ getSlotLength sp
f = unActiveSlotCoefficient (getActiveSlotCoefficient sp)
onExit
:: Either SomeException a
-> IO ()
onExit = traceWith tr . \case
Right _ -> MsgGCFinished
Left e -> case asyncExceptionFromException e of
Just ThreadKilled -> MsgGCThreadKilled
Just UserInterrupt -> MsgGCUserInterrupt
_ -> MsgGCUnhandledException $ pretty $ show e
gcDelistedPools
:: TVar PoolMetadataGCStatus
-> Tracer IO StakePoolLog
-> DBLayer IO
-> IO (Maybe [PoolId]) -- ^ delisted pools fetcher
-> IO ()
gcDelistedPools gcStatus tr DBLayer{..} fetchDelisted = forever $ do
lastGC <- atomically readLastMetadataGC
currentTime <- getPOSIXTime
case lastGC of
Nothing -> pure ()
Just gc -> STM.atomically $ writeTVar gcStatus (HasRun gc)
let timeSinceLastGC = fmap (currentTime -) lastGC
sixHours = posixDayLength / 4
when (maybe True (> sixHours) timeSinceLastGC) $ do
delistedPools <- fmap (fromMaybe []) fetchDelisted
STM.atomically $ writeTVar gcStatus (HasRun currentTime)
atomically $ do
putLastMetadataGC currentTime
putDelistedPools delistedPools
-- Sleep for 60 seconds. This is useful in case
-- something else is modifying the last sync time
-- in the database.
let ms = (* 1_000_000)
let sleepTime = ms 60
traceWith tr $ MsgGCTakeBreak sleepTime
threadDelay sleepTime
pure ()
data StakePoolLog
= MsgFollow FollowLog
| MsgStartMonitoring [BlockHeader]
| MsgHaltMonitoring
| MsgCrashMonitoring
| MsgRollingBackTo SlotNo
| MsgStakePoolGarbageCollection PoolGarbageCollectionInfo
| MsgStakePoolRegistration PoolRegistrationCertificate
| MsgStakePoolRetirement PoolRetirementCertificate
| MsgErrProduction ErrPointAlreadyExists
| MsgFetchPoolMetadata StakePoolMetadataFetchLog
| MsgFetchTakeBreak Int
| MsgGCTakeBreak Int
| MsgGCFinished
| MsgGCThreadKilled
| MsgGCUserInterrupt
| MsgGCUnhandledException Text
| MsgSMASHUnreachable
deriving (Show, Eq)
data PoolGarbageCollectionInfo = PoolGarbageCollectionInfo
{ currentEpoch :: EpochNo
-- ^ The current epoch at the point in time the garbage collector
-- was invoked.
, latestRetirementEpoch :: EpochNo
-- ^ The latest retirement epoch for which garbage collection will be
-- performed. The garbage collector will remove all pools that have an
-- active retirement epoch equal to or earlier than this epoch.
}
deriving (Eq, Show)
instance HasPrivacyAnnotation StakePoolLog
instance HasSeverityAnnotation StakePoolLog where
getSeverityAnnotation = \case
MsgFollow e -> getSeverityAnnotation e
MsgStartMonitoring{} -> Info
MsgHaltMonitoring{} -> Info
MsgCrashMonitoring{} -> Error
MsgRollingBackTo{} -> Info
MsgStakePoolGarbageCollection{} -> Debug
MsgStakePoolRegistration{} -> Info
MsgStakePoolRetirement{} -> Info
MsgErrProduction{} -> Error
MsgFetchPoolMetadata e -> getSeverityAnnotation e
MsgFetchTakeBreak{} -> Debug
MsgGCTakeBreak{} -> Debug
MsgGCFinished{} -> Debug
MsgGCThreadKilled{} -> Debug
MsgGCUserInterrupt{} -> Debug
MsgGCUnhandledException{} -> Debug
MsgSMASHUnreachable{} -> Warning
instance ToText StakePoolLog where
toText = \case
MsgFollow e ->
toText e
MsgStartMonitoring cursor -> mconcat
[ "Monitoring stake pools. Currently at "
, case cursor of
[] -> "genesis"
_ -> pretty (last cursor)
]
MsgHaltMonitoring ->
"Stopping stake pool monitoring as requested."
MsgCrashMonitoring -> mconcat
[ "Chain follower exited with error. "
, "Worker will no longer monitor stake pools."
]
MsgRollingBackTo point ->
"Rolling back to " <> pretty point
MsgStakePoolGarbageCollection info -> mconcat
[ "Performing garbage collection of retired stake pools. "
, "Currently in epoch "
, toText (currentEpoch info)
, ". Removing all pools that retired in or before epoch "
, toText (latestRetirementEpoch info)
, "."
]
MsgStakePoolRegistration cert ->
"Discovered stake pool registration: " <> pretty cert
MsgStakePoolRetirement cert ->
"Discovered stake pool retirement: " <> pretty cert
MsgErrProduction (ErrPointAlreadyExists blk) -> mconcat
[ "Couldn't store production for given block before it conflicts "
, "with another block. Conflicting block header is: ", pretty blk
]
MsgFetchPoolMetadata e ->
toText e
MsgFetchTakeBreak delay -> mconcat
[ "Taking a little break from fetching metadata, "
, "back to it in about "
, pretty (fixedF 1 (toRational delay / 1000000)), "s"
]
MsgGCTakeBreak delay -> mconcat
[ "Taking a little break from GCing delisted metadata pools, "
, "back to it in about "
, pretty (fixedF 1 (toRational delay / 1_000_000)), "s"
]
MsgGCFinished -> "GC thread has exited: main action is over."
MsgGCThreadKilled -> "GC thread has exited: killed by parent."
MsgGCUserInterrupt -> "GC thread has exited: killed by user."
MsgGCUnhandledException err ->
"GC thread has exited unexpectedly: " <> err
MsgSMASHUnreachable -> mconcat
["The SMASH server is unreachable or unhealthy."
, "Metadata monitoring thread aborting."
]