-
Notifications
You must be signed in to change notification settings - Fork 721
/
Logging.hs
320 lines (290 loc) · 13.5 KB
/
Logging.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
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Cardano.Node.Configuration.Logging
( LoggingLayer (..)
, createLoggingLayer
, nodeBasicInfo
, shutdownLoggingLayer
, traceCounter
-- re-exports
, Trace
, Configuration
, LoggerName
, Severity (..)
, mkLOMeta
, LOMeta (..)
, LOContent (..)
) where
import Cardano.Prelude hiding (trace)
import qualified Control.Concurrent.Async as Async
import Control.Exception.Safe (MonadCatch)
import Control.Monad.Trans.Except.Extra (catchIOExceptT)
import Control.Tracer
import Data.List (nub)
import Data.Text (pack)
import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Version (showVersion)
import Cardano.BM.Backend.Aggregation (plugin)
import Cardano.BM.Backend.EKGView (plugin)
import Cardano.BM.Backend.Monitoring (plugin)
import Cardano.BM.Backend.Switchboard (Switchboard)
import qualified Cardano.BM.Backend.Switchboard as Switchboard
import Cardano.BM.Backend.TraceForwarder (plugin)
import Cardano.BM.Configuration (Configuration)
import qualified Cardano.BM.Configuration as Config
import qualified Cardano.BM.Configuration.Model as Config
import Cardano.BM.Data.Aggregated (Measurable (..))
import Cardano.BM.Data.Backend (Backend, BackendKind (..))
import Cardano.BM.Data.LogItem (LOContent (..), LOMeta (..), LoggerName)
import qualified Cardano.BM.Observer.Monadic as Monadic
import qualified Cardano.BM.Observer.STM as Stm
import Cardano.BM.Plugin (loadPlugin)
#if defined(SYSTEMD)
import Cardano.BM.Scribe.Systemd (plugin)
#endif
import Cardano.BM.Setup (setupTrace_, shutdown)
import Cardano.BM.Stats
import Cardano.BM.Stats.Resources
import qualified Cardano.BM.Trace as Trace
import Cardano.BM.Tracing
import qualified Cardano.Chain.Genesis as Gen
import Cardano.Slotting.Slot (EpochSize (..))
import Ouroboros.Consensus.Block (BlockProtocol)
import qualified Ouroboros.Consensus.BlockchainTime.WallClock.Types as WCT
import Ouroboros.Consensus.Byron.Ledger.Conversions
import qualified Ouroboros.Consensus.Cardano as Consensus
import Ouroboros.Consensus.Cardano.Block
import Ouroboros.Consensus.Cardano.CanHardFork
import qualified Ouroboros.Consensus.Config as Consensus
import Ouroboros.Consensus.Config.SupportsNode (ConfigSupportsNode (..))
import Ouroboros.Consensus.HardFork.Combinator.Degenerate
import Ouroboros.Consensus.Node.ProtocolInfo
import Ouroboros.Consensus.Shelley.Ledger.Ledger
import qualified Shelley.Spec.Ledger.API as SL
import Cardano.Config.Git.Rev (gitRev)
import Cardano.Node.Configuration.POM (NodeConfiguration (..), ncProtocol)
import Cardano.Node.Types
import Cardano.Tracing.OrphanInstances.Common ()
import Paths_cardano_node (version)
--------------------------------
-- Layer
--------------------------------
-- | The LoggingLayer interface that we can expose.
-- We want to do this since we want to be able to mock out any function tied to logging.
--
-- The good side of this is that _each function has it's own effects_
-- and that is ideal for tracking the functions effects and constraining
-- the user (programmer) of those function to use specific effects in them.
-- https://github.com/input-output-hk/cardano-sl/blob/develop/util/src/Pos/Util/Log/LogSafe.hs
data LoggingLayer = LoggingLayer
{ llBasicTrace :: forall m. (MonadIO m) => Trace m Text
, llLogDebug :: forall m a. (MonadIO m, Show a) => Trace m a -> a -> m ()
, llLogInfo :: forall m a. (MonadIO m, Show a) => Trace m a -> a -> m ()
, llLogNotice :: forall m a. (MonadIO m, Show a) => Trace m a -> a -> m ()
, llLogWarning :: forall m a. (MonadIO m, Show a) => Trace m a -> a -> m ()
, llLogError :: forall m a. (MonadIO m, Show a) => Trace m a -> a -> m ()
, llAppendName :: forall m a. (Show a) => LoggerName -> Trace m a -> Trace m a
, llBracketMonadIO :: forall a t. (Show a) => Trace IO a -> Severity -> Text -> IO t -> IO t
, llBracketMonadM
:: forall m a t. (MonadCatch m, MonadIO m, Show a)
=> Trace m a -> Severity -> Text -> m t -> m t
, llBracketMonadX
:: forall m a t. (MonadIO m, Show a) => Trace m a -> Severity -> Text -> m t -> m t
, llBracketStmIO :: forall a t. (Show a) => Trace IO a -> Severity -> Text -> STM t -> IO t
, llBracketStmLogIO
:: forall a t. (Show a)
=> Trace IO a -> Severity -> Text -> STM (t,[(LOMeta, LOContent a)]) -> IO t
, llConfiguration :: Configuration
, llAddBackend :: Backend Text -> BackendKind -> IO ()
, llSwitchboard :: Switchboard Text
}
--------------------------------
-- Feature
--------------------------------
-- | Either parse a filepath into a logging 'Configuration',
-- or supply a mute 'Configuration'.
loggingCLIConfiguration
:: Maybe FilePath
-> ExceptT ConfigError IO Configuration
loggingCLIConfiguration = maybe emptyConfig readConfig
where
readConfig :: FilePath -> ExceptT ConfigError IO Configuration
readConfig fp =
catchIOExceptT (Config.setup fp) $ \(_ :: IOException) -> ConfigErrorFileNotFound fp
emptyConfig :: ExceptT ConfigError IO Configuration
emptyConfig = liftIO $ do
c <- Config.empty
Config.setMinSeverity c Info
pure c
-- | Create logging feature for `cardano-node`
createLoggingLayer
:: Text
-> NodeConfiguration
-> Consensus.Protocol IO blk (BlockProtocol blk)
-> ExceptT ConfigError IO LoggingLayer
createLoggingLayer ver nodeConfig' p = do
logConfig <- loggingCLIConfiguration $
if ncLoggingSwitch nodeConfig'
-- Re-interpret node config again, as logging 'Configuration':
then Just . unConfigPath $ ncConfigFile nodeConfig'
else Nothing
-- These have to be set before the switchboard is set up.
liftIO $ do
Config.setTextOption logConfig "appversion" ver
Config.setTextOption logConfig "appcommit" gitRev
(baseTrace, switchBoard) <- liftIO $ setupTrace_ logConfig "cardano"
let loggingEnabled :: Bool
loggingEnabled = ncLoggingSwitch nodeConfig'
trace :: Trace IO Text
trace = if loggingEnabled
then baseTrace
else Trace.nullTracer
when loggingEnabled $ liftIO $
loggingPreInit nodeConfig' logConfig switchBoard trace
pure $ mkLogLayer logConfig switchBoard trace
where
loggingPreInit
:: NodeConfiguration
-> Configuration
-> Switchboard Text
-> Trace IO Text
-> IO ()
loggingPreInit nodeConfig logConfig switchBoard trace = do
Config.getEKGBindAddr logConfig >>= \mbEndpoint ->
when (isJust mbEndpoint) $
Cardano.BM.Backend.EKGView.plugin logConfig trace switchBoard
>>= loadPlugin switchBoard
Config.getForwardTo logConfig >>= \forwardTo ->
when (isJust forwardTo) $ do
-- Since the configuration contains 'traceForwardTo' section,
-- node's information (metrics/peers/errors) should be forwarded
-- to an external process (for example, RTView).
-- Activate TraceForwarder plugin (there is no need to add 'TraceForwarderBK'
-- to 'setupBackends' list).
nodeStartTime <- getCurrentTime
Cardano.BM.Backend.TraceForwarder.plugin logConfig
trace
switchBoard
"forwarderMinSeverity"
(nodeBasicInfo nodeConfig p nodeStartTime)
>>= loadPlugin switchBoard
-- Forward all the metrics/peers/errors to 'TraceForwarderBK' using 'mapBackends'.
-- If 'TraceForwarderBK' is already added in 'mapBackends' - ignore it.
let metricsLogger = "cardano.node.metrics" -- All metrics and peers info are here.
errorsLoggers = "cardano.node" -- All errors (messages with 'Warning+' severity) are here.
forM_ [metricsLogger, errorsLoggers] $ \loggerName ->
Config.getBackends logConfig loggerName >>= \backends ->
when (TraceForwarderBK `notElem` backends) $
Config.setBackends logConfig loggerName $ Just (TraceForwarderBK : backends)
Cardano.BM.Backend.Aggregation.plugin logConfig trace switchBoard
>>= loadPlugin switchBoard
Cardano.BM.Backend.Monitoring.plugin logConfig trace switchBoard
>>= loadPlugin switchBoard
#if defined(SYSTEMD)
Cardano.BM.Scribe.Systemd.plugin logConfig trace switchBoard "cardano"
>>= loadPlugin switchBoard
#endif
when (ncLogMetrics nodeConfig) $
-- Record node metrics, if configured
startCapturingMetrics trace
mkLogLayer :: Configuration -> Switchboard Text -> Trace IO Text -> LoggingLayer
mkLogLayer logConfig switchBoard trace =
LoggingLayer
{ llBasicTrace = Trace.natTrace liftIO trace
, llLogDebug = Trace.logDebug
, llLogInfo = Trace.logInfo
, llLogNotice = Trace.logNotice
, llLogWarning = Trace.logWarning
, llLogError = Trace.logError
, llAppendName = Trace.appendName
, llBracketMonadIO = Monadic.bracketObserveIO logConfig
, llBracketMonadM = Monadic.bracketObserveM logConfig
, llBracketMonadX = Monadic.bracketObserveX logConfig
, llBracketStmIO = Stm.bracketObserveIO logConfig
, llBracketStmLogIO = Stm.bracketObserveLogIO logConfig
, llConfiguration = logConfig
, llAddBackend = Switchboard.addExternalBackend switchBoard
, llSwitchboard = switchBoard
}
startCapturingMetrics :: Trace IO Text -> IO ()
startCapturingMetrics tr = do
void . Async.async . forever $ do
readResourceStats
>>= maybe (pure ())
(traceResourceStats
(appendName "node" tr))
threadDelay 1000000 -- TODO: make configurable
traceResourceStats :: Trace IO Text -> ResourceStats -> IO ()
traceResourceStats tr rs = do
traceWith (toLogObject' NormalVerbosity $ appendName "resources" tr) rs
traceCounter "Stat.cputicks" tr . fromIntegral $ rCentiCpu rs
traceCounter "Mem.resident" tr . fromIntegral $ rRSS rs
traceCounter "RTS.gcLiveBytes" tr . fromIntegral $ rLive rs
traceCounter "RTS.gcMajorNum" tr . fromIntegral $ rGcsMajor rs
traceCounter "RTS.gcMinorNum" tr . fromIntegral $ rGcsMinor rs
traceCounter "RTS.gcticks" tr . fromIntegral $ rCentiGC rs
traceCounter "RTS.mutticks" tr . fromIntegral $ rCentiMut rs
traceCounter "Stat.threads" tr . fromIntegral $ rThreads rs
traceCounter
:: Text
-> Trace IO Text
-> Int
-> IO ()
traceCounter logValueName tracer aCounter = do
meta <- mkLOMeta Notice Public
Trace.traceNamedObject
(appendName "metrics" tracer)
(meta, LogValue logValueName (PureI $ fromIntegral aCounter))
shutdownLoggingLayer :: LoggingLayer -> IO ()
shutdownLoggingLayer = shutdown . llSwitchboard
-- The node provides the basic node's information for TraceForwarderBK.
-- It will be sent once TraceForwarderBK is connected to an external process
-- (for example, RTView).
nodeBasicInfo :: NodeConfiguration
-> Consensus.Protocol IO blk (BlockProtocol blk)
-> UTCTime
-> IO [LogObject Text]
nodeBasicInfo nc p nodeStartTime' = do
meta <- mkLOMeta Notice Public
let cfg = pInfoConfig $ Consensus.protocolInfo p
protocolDependentItems =
case p of
Consensus.ProtocolByron {} ->
let DegenLedgerConfig cfgByron = Consensus.configLedger cfg
in getGenesisValuesByron cfg cfgByron
Consensus.ProtocolShelley {} ->
let DegenLedgerConfig cfgShelley = Consensus.configLedger cfg
in getGenesisValues "Shelley" cfgShelley
Consensus.ProtocolCardano {} ->
let CardanoLedgerConfig cfgByron cfgShelley cfgAllegra cfgMary = Consensus.configLedger cfg
in getGenesisValuesByron cfg cfgByron
++ getGenesisValues "Shelley" cfgShelley
++ getGenesisValues "Allegra" cfgAllegra
++ getGenesisValues "Mary" cfgMary
items = nub $
[ ("protocol", pack . protocolName $ ncProtocol nc)
, ("version", pack . showVersion $ version)
, ("commit", gitRev)
, ("nodeStartTime", show nodeStartTime')
] ++ protocolDependentItems
logObjects =
map (\(nm, msg) -> LogObject ("basicInfo." <> nm) meta (LogMessage msg)) items
return logObjects
where
getGenesisValuesByron cfg config =
let genesis = byronLedgerConfig config
in [ ("systemStartTime", show (WCT.getSystemStart . getSystemStart $ Consensus.configBlock cfg))
, ("slotLengthByron", show (WCT.getSlotLength . fromByronSlotLength $ genesisSlotLength genesis))
, ("epochLengthByron", show (unEpochSize . fromByronEpochSlots $ Gen.configEpochSlots genesis))
]
getGenesisValues era config =
let genesis = shelleyLedgerGenesis $ shelleyLedgerConfig config
in [ ("systemStartTime", show (SL.sgSystemStart genesis))
, ("slotLength" <> era, show (WCT.getSlotLength . WCT.mkSlotLength $ SL.sgSlotLength genesis))
, ("epochLength" <> era, show (unEpochSize . SL.sgEpochLength $ genesis))
, ("slotsPerKESPeriod" <> era, show (SL.sgSlotsPerKESPeriod genesis))
]