-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathConfig.hs
557 lines (510 loc) · 16.3 KB
/
Config.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
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Test.Cardano.Db.Mock.Config (
Config (..),
DBSyncEnv (..),
CommandLineArgs (..),
WithConfigArgs (..),
initCommandLineArgs,
babbageConfigDir,
conwayConfigDir,
alonzoConfigDir,
shelleyConfigDir,
emptyMetricsSetters,
fingerprintRoot,
getDBSyncPGPass,
getPoolLayer,
mkConfig,
mkSyncNodeConfig,
mkConfigDir,
mkFingerPrint,
mkMutableDir,
mkDBSyncEnv,
mkShelleyCredentials,
mkSyncNodeParams,
pollDBSync,
prepareFingerprintFile,
queryDBSync,
recreateDir,
rootTestDir,
stopDBSync,
stopDBSyncIfRunning,
startDBSync,
withDBSyncEnv,
withFullConfig,
withFullConfigAndDropDB,
withFullConfigLogsDropDB,
withFullConfigAndLogs,
withCustomConfigAndLogsAndDropDB,
withCustomConfig,
withCustomConfigAndDropDB,
withCustomConfigAndLogs,
withFullConfig',
replaceConfigFile,
) where
import Cardano.Api (NetworkMagic (..))
import qualified Cardano.Db as Db
import Cardano.DbSync
import Cardano.DbSync.Config
import Cardano.DbSync.Config.Cardano
import Cardano.DbSync.Error (runOrThrowIO)
import Cardano.DbSync.Types (CardanoBlock, MetricSetters (..))
import Cardano.Mock.ChainSync.Server
import Cardano.Mock.Forging.Interpreter
import Cardano.Node.Protocol.Shelley (readLeaderCredentials)
import Cardano.Node.Types (ProtocolFilepaths (..))
import Cardano.Prelude (ReaderT, panic, stderr, textShow)
import Cardano.SMASH.Server.PoolDataLayer
import Control.Concurrent.Async (Async, async, cancel, poll)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TMVar (
TMVar,
newEmptyTMVarIO,
takeTMVar,
tryPutTMVar,
tryReadTMVar,
)
import Control.Exception (SomeException, bracket)
import Control.Monad (void)
import Control.Monad.Extra (eitherM)
import Control.Monad.Logger (NoLoggingT, runNoLoggingT)
import Control.Monad.Trans.Except.Extra (runExceptT)
import Control.Tracer (nullTracer)
import Data.Text (Text)
import Database.Persist.Postgresql (createPostgresqlPool)
import Database.Persist.Sql (SqlBackend)
import Ouroboros.Consensus.Block.Forging
import Ouroboros.Consensus.Config (TopLevelConfig)
import qualified Ouroboros.Consensus.Node.ProtocolInfo as Consensus
import Ouroboros.Consensus.Shelley.Eras (StandardCrypto)
import Ouroboros.Consensus.Shelley.Node (ShelleyLeaderCredentials)
import System.Directory (createDirectoryIfMissing, removePathForcibly)
import System.FilePath.Posix (takeDirectory, (</>))
import System.IO.Silently (hSilence)
data Config = Config
{ topLevelConfig :: TopLevelConfig CardanoBlock
, protocolInfo :: Consensus.ProtocolInfo CardanoBlock
, protocolInfoForging :: Consensus.ProtocolInfo CardanoBlock
, protocolInfoForger :: [BlockForging IO CardanoBlock]
, syncNodeParams :: SyncNodeParams
}
data DBSyncEnv = DBSyncEnv
{ dbSyncParams :: SyncNodeParams
, dbSyncConfig :: SyncNodeConfig
, partialRunDbSync :: SyncNodeParams -> SyncNodeConfig -> IO ()
, dbSyncThreadVar :: TMVar (Async ())
}
data CommandLineArgs = CommandLineArgs
{ claConfigFilename :: FilePath
, claEpochDisabled :: Bool
, claHasCache :: Bool
, claHasLedger :: Bool
, claSkipFix :: Bool
, claOnlyFix :: Bool
, claForceIndexes :: Bool
, claHasMultiAssets :: Bool
, claHasMetadata :: Bool
, claHasPlutusExtra :: Bool
, claHasOffChainData :: Bool
, claTurboMode :: Bool
, claFullMode :: Bool
, claMigrateConsumed :: Bool
, claPruneTxOut :: Bool
, claBootstrap :: Bool
}
data WithConfigArgs = WithConfigArgs
{ hasFingerprint :: Bool
, shouldLog :: Bool
, shouldDropDB :: Bool
}
babbageConfigDir :: FilePath
babbageConfigDir = "config"
conwayConfigDir :: FilePath
conwayConfigDir = "config-conway"
alonzoConfigDir :: FilePath
alonzoConfigDir = "config-alonzo"
shelleyConfigDir :: FilePath
shelleyConfigDir = "config-shelley"
rootTestDir :: FilePath
rootTestDir = "test/testfiles"
mkMutableDir :: FilePath -> FilePath
mkMutableDir testLabel = rootTestDir </> "temp" </> testLabel
mkConfigDir :: FilePath -> FilePath
mkConfigDir config = rootTestDir </> config
fingerprintRoot :: FilePath
fingerprintRoot = rootTestDir </> "fingerprint"
mkFingerPrint :: FilePath -> FilePath
mkFingerPrint testLabel = fingerprintRoot </> testLabel
mkDBSyncEnv ::
SyncNodeParams ->
SyncNodeConfig ->
(SyncNodeParams -> SyncNodeConfig -> IO ()) ->
IO DBSyncEnv
mkDBSyncEnv params cfg pRunDbSync = do
runningVar <- newEmptyTMVarIO
pure $
DBSyncEnv
{ dbSyncParams = params
, dbSyncConfig = cfg
, partialRunDbSync = pRunDbSync
, dbSyncThreadVar = runningVar
}
stopDBSync :: DBSyncEnv -> IO ()
stopDBSync env = do
thr <- atomically $ tryReadTMVar (dbSyncThreadVar env)
case thr of
Nothing -> error "Could not cancel db-sync when it's not running"
Just tmVar -> do
cancel tmVar
-- make it empty
void . atomically $ takeTMVar (dbSyncThreadVar env)
pure ()
stopDBSyncIfRunning :: DBSyncEnv -> IO ()
stopDBSyncIfRunning env = do
thr <- atomically $ tryReadTMVar (dbSyncThreadVar env)
case thr of
Nothing -> pure ()
Just tmVar -> do
cancel tmVar
-- make it empty
void . atomically $ takeTMVar (dbSyncThreadVar env)
startDBSync :: DBSyncEnv -> IO ()
startDBSync env = do
thr <- atomically $ tryReadTMVar (dbSyncThreadVar env)
case thr of
Just _a -> error "db-sync already running"
Nothing -> do
let appliedRunDbSync = partialRunDbSync env (dbSyncParams env) (dbSyncConfig env)
-- we async the fully applied runDbSync here ad put it into the thread
asyncApplied <- async appliedRunDbSync
void . atomically $ tryPutTMVar (dbSyncThreadVar env) asyncApplied
pollDBSync :: DBSyncEnv -> IO (Maybe (Either SomeException ()))
pollDBSync env = do
thr <- atomically $ tryReadTMVar (dbSyncThreadVar env)
case thr of
Nothing -> error "Could not poll db-sync when it's not running"
Just a -> poll a
withDBSyncEnv :: IO DBSyncEnv -> (DBSyncEnv -> IO a) -> IO a
withDBSyncEnv mkEnv = bracket mkEnv stopDBSyncIfRunning
getDBSyncPGPass :: DBSyncEnv -> Db.PGPassSource
getDBSyncPGPass = enpPGPassSource . dbSyncParams
queryDBSync :: DBSyncEnv -> ReaderT SqlBackend (NoLoggingT IO) a -> IO a
queryDBSync env = Db.runWithConnectionNoLogging (getDBSyncPGPass env)
getPoolLayer :: DBSyncEnv -> IO PoolDataLayer
getPoolLayer env = do
pgconfig <- runOrThrowIO $ Db.readPGPass (enpPGPassSource $ dbSyncParams env)
pool <- runNoLoggingT $ createPostgresqlPool (Db.toConnectionString pgconfig) 1 -- Pool size of 1 for tests
pure $
postgresqlPoolDataLayer
nullTracer
pool
mkConfig :: FilePath -> FilePath -> CommandLineArgs -> SyncNodeConfig -> IO Config
mkConfig staticDir mutableDir cmdLineArgs config = do
let cfgDir = mkConfigDir staticDir
genCfg <- runOrThrowIO $ runExceptT (readCardanoGenesisConfig config)
let (pInfoDbSync, _) = mkProtocolInfoCardano genCfg []
creds <- mkShelleyCredentials $ cfgDir </> "pools" </> "bulk1.creds"
let (pInfoForger, forging) = mkProtocolInfoCardano genCfg creds
forging' <- forging
syncPars <- mkSyncNodeParams staticDir mutableDir cmdLineArgs
pure $ Config (Consensus.pInfoConfig pInfoDbSync) pInfoDbSync pInfoForger forging' syncPars
mkSyncNodeConfig :: FilePath -> CommandLineArgs -> IO SyncNodeConfig
mkSyncNodeConfig configFilePath cmdLineArgs =
readSyncNodeConfig $ mkConfigFile configDir configFilename
where
configFilename = claConfigFilename cmdLineArgs
configDir = mkConfigDir configFilePath
mkShelleyCredentials :: FilePath -> IO [ShelleyLeaderCredentials StandardCrypto]
mkShelleyCredentials bulkFile = do
eitherM (panic . textShow) pure $ runExceptT $ readLeaderCredentials (Just protFiles)
where
protFiles =
ProtocolFilepaths
{ byronCertFile = Nothing
, byronKeyFile = Nothing
, shelleyKESFile = Nothing
, shelleyVRFFile = Nothing
, shelleyCertFile = Nothing
, shelleyBulkCredsFile = Just bulkFile
}
-- | staticDir can be shared by tests running in parallel. mutableDir not.
mkSyncNodeParams :: FilePath -> FilePath -> CommandLineArgs -> IO SyncNodeParams
mkSyncNodeParams staticDir mutableDir CommandLineArgs {..} = do
pgconfig <- runOrThrowIO Db.readPGPassDefault
pure $
SyncNodeParams
{ enpConfigFile = mkConfigFile staticDir claConfigFilename
, enpSocketPath = SocketPath $ mutableDir </> ".socket"
, enpMaybeLedgerStateDir = Just $ LedgerStateDir $ mutableDir </> "ledger-states"
, enpMigrationDir = MigrationDir "../schema"
, enpPGPassSource = Db.PGPassCached pgconfig
, enpEpochDisabled = claEpochDisabled
, enpHasCache = claHasCache
, enpSkipFix = claSkipFix
, enpOnlyFix = claOnlyFix
, enpForceIndexes = claForceIndexes
, enpHasInOut = True
, enpSnEveryFollowing = 35
, enpSnEveryLagging = 35
, enpMaybeRollback = Nothing
}
mkConfigFile :: FilePath -> FilePath -> ConfigFile
mkConfigFile staticDir cliConfigFilename =
ConfigFile $ staticDir </> cliConfigFilename
initCommandLineArgs :: CommandLineArgs
initCommandLineArgs =
CommandLineArgs
{ claConfigFilename = "test-db-sync-config.json"
, claEpochDisabled = True
, claHasCache = True
, claHasLedger = True
, claSkipFix = True
, claOnlyFix = False
, claForceIndexes = False
, claHasMultiAssets = True
, claHasMetadata = True
, claHasPlutusExtra = True
, claHasOffChainData = True
, claTurboMode = False
, claFullMode = True
, claMigrateConsumed = False
, claPruneTxOut = False
, claBootstrap = False
}
emptyMetricsSetters :: MetricSetters
emptyMetricsSetters =
MetricSetters
{ metricsSetNodeBlockHeight = \_ -> pure ()
, metricsSetDbQueueLength = \_ -> pure ()
, metricsSetDbBlockHeight = \_ -> pure ()
, metricsSetDbSlotHeight = \_ -> pure ()
}
withFullConfig ::
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withFullConfig =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = False
, shouldDropDB = False
}
)
initCommandLineArgs
Nothing
-- this function needs to be used where the schema needs to be rebuilt
withFullConfigAndDropDB ::
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withFullConfigAndDropDB =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = False
, shouldDropDB = True
}
)
initCommandLineArgs
Nothing
withFullConfigLogsDropDB ::
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withFullConfigLogsDropDB =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = True
, shouldDropDB = True
}
)
initCommandLineArgs
Nothing
withFullConfigAndLogs ::
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withFullConfigAndLogs =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = True
, shouldDropDB = False
}
)
initCommandLineArgs
Nothing
withCustomConfig ::
CommandLineArgs ->
-- | custom SyncNodeConfig
Maybe SyncNodeConfig ->
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withCustomConfig =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = False
, shouldDropDB = False
}
)
withCustomConfigAndDropDB ::
CommandLineArgs ->
-- | custom SyncNodeConfig
Maybe SyncNodeConfig ->
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withCustomConfigAndDropDB =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = False
, shouldDropDB = True
}
)
-- This is a usefull function to be able to see logs from DBSync when writing/debuging tests
withCustomConfigAndLogs ::
CommandLineArgs ->
-- | custom SyncNodeConfig
Maybe SyncNodeConfig ->
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withCustomConfigAndLogs =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = True
, shouldDropDB = False
}
)
withCustomConfigAndLogsAndDropDB ::
CommandLineArgs ->
-- | custom SyncNodeConfig
Maybe SyncNodeConfig ->
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withCustomConfigAndLogsAndDropDB =
withFullConfig'
( WithConfigArgs
{ hasFingerprint = True
, shouldLog = True
, shouldDropDB = True
}
)
withFullConfig' ::
WithConfigArgs ->
CommandLineArgs ->
-- | custom SyncNodeConfig
Maybe SyncNodeConfig ->
-- | config filepath
FilePath ->
-- | test label
FilePath ->
(Interpreter -> ServerHandle IO CardanoBlock -> DBSyncEnv -> IO a) ->
IOManager ->
[(Text, Text)] ->
IO a
withFullConfig' WithConfigArgs {..} cmdLineArgs mSyncNodeConfig configFilePath testLabelFilePath action iom migr = do
recreateDir mutableDir
-- check if custom syncNodeConfigs have been passed or not
syncNodeConfig <-
case mSyncNodeConfig of
Just snc -> pure snc
Nothing -> mkSyncNodeConfig configFilePath cmdLineArgs
cfg <- mkConfig configFilePath mutableDir cmdLineArgs syncNodeConfig
fingerFile <- if hasFingerprint then Just <$> prepareFingerprintFile testLabelFilePath else pure Nothing
let dbsyncParams = syncNodeParams cfg
trce <-
if shouldLog
then configureLogging syncNodeConfig "db-sync-node"
else pure nullTracer
-- runDbSync is partially applied so we can pass in syncNodeParams at call site / within tests
let partialDbSyncRun params cfg' = runDbSync emptyMetricsSetters migr iom trce params cfg' True
initSt = Consensus.pInfoInitLedger $ protocolInfo cfg
withInterpreter (protocolInfoForging cfg) (protocolInfoForger cfg) nullTracer fingerFile $ \interpreter -> do
-- TODO: get 42 from config
withServerHandle @CardanoBlock
iom
(topLevelConfig cfg)
initSt
(NetworkMagic 42)
(unSocketPath (enpSocketPath $ syncNodeParams cfg))
$ \mockServer ->
-- we dont fork dbsync here. Just prepare it as an action
withDBSyncEnv (mkDBSyncEnv dbsyncParams syncNodeConfig partialDbSyncRun) $ \dbSyncEnv -> do
let pgPass = getDBSyncPGPass dbSyncEnv
tableNames <- Db.getAllTablleNames pgPass
-- We only want to create the table schema once for the tests so here we check
-- if there are any table names.
if null tableNames || shouldDropDB
then void . hSilence [stderr] $ Db.recreateDB pgPass
else void . hSilence [stderr] $ Db.truncateTables pgPass tableNames
action interpreter mockServer dbSyncEnv
where
mutableDir = mkMutableDir testLabelFilePath
prepareFingerprintFile :: FilePath -> IO FilePath
prepareFingerprintFile testLabel = do
createDirectoryIfMissing True fingerprintRoot
pure fingerprintFile
where
fingerprintFile = mkFingerPrint testLabel
recreateDir :: FilePath -> IO ()
recreateDir path = do
removePathForcibly path
createDirectoryIfMissing True path
replaceConfigFile :: FilePath -> DBSyncEnv -> IO DBSyncEnv
replaceConfigFile newFilename dbSync@DBSyncEnv {..} = do
cfg <- readSyncNodeConfig $ mkConfigFile configDir newFilename
pure $ dbSync {dbSyncParams = newParams, dbSyncConfig = cfg}
where
configDir = mkConfigDir . takeDirectory . unConfigFile . enpConfigFile $ dbSyncParams
newParams =
dbSyncParams {enpConfigFile = ConfigFile $ configDir </> newFilename}