-
Notifications
You must be signed in to change notification settings - Fork 86
/
Server2.hs
261 lines (241 loc) · 9.82 KB
/
Server2.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
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
-- 'runResponder' is using a redundant constraint.
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
-- | Server implementation based on 'ConnectionManager'
--
module Ouroboros.Network.Server2
( ServerArguments (..)
, InboundGovernorObservableState (..)
, newObservableStateVar
, newObservableStateVarIO
, newObservableStateVarFromSeed
-- * Run server
, run
-- * PrunePolicy
, randomPrunePolicy
-- * Trace
, ServerTrace (..)
, AcceptConnectionsPolicyTrace (..)
, RemoteSt (..)
, RemoteTransition
, RemoteTransitionTrace
-- * ControlChannel
, module ControlChannel
) where
import Control.Monad.Class.MonadAsync
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadSTM.Strict
import Control.Monad.Class.MonadThrow hiding (handle)
import Control.Monad.Class.MonadTime
import Control.Monad.Class.MonadTimer
import Control.Tracer (Tracer, contramap, traceWith)
import Data.ByteString.Lazy (ByteString)
import Data.Void (Void)
import Data.List (intercalate)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
#if defined(mingw32_HOST_OS)
import System.IO.Error
#else
import GHC.IO.Exception
import Foreign.C.Error
#endif
import Ouroboros.Network.ConnectionManager.Types
import Ouroboros.Network.ConnectionHandler
import Ouroboros.Network.InboundGovernor
import Ouroboros.Network.InboundGovernor.ControlChannel
import qualified Ouroboros.Network.InboundGovernor.ControlChannel as ControlChannel
import Ouroboros.Network.Mux hiding (ControlMessage)
import Ouroboros.Network.Server.RateLimiting
import Ouroboros.Network.Snocket
--
-- Server API
--
-- | Server static configuration.
--
data ServerArguments (muxMode :: MuxMode) socket peerAddr versionNumber bytes m a b =
ServerArguments {
serverSockets :: NonEmpty socket,
serverSnocket :: Snocket m socket peerAddr,
serverTracer :: Tracer m (ServerTrace peerAddr),
serverTrTracer :: Tracer m (RemoteTransitionTrace peerAddr),
serverInboundGovernorTracer :: Tracer m (InboundGovernorTrace peerAddr),
serverConnectionLimits :: AcceptedConnectionsLimit,
serverConnectionManager :: MuxConnectionManager muxMode socket peerAddr
versionNumber bytes m a b,
-- | Time for which all protocols need to be idle to trigger
-- 'DemotedToCold' transition.
--
serverInboundIdleTimeout :: DiffTime,
-- | Server control var is passed as an argument; this allows to use the
-- server to run and manage responders which needs to be started on
-- inbound connections.
--
serverControlChannel :: ServerControlChannel muxMode peerAddr bytes m a b,
-- | Observable mutable s tate.
--
serverObservableStateVar :: StrictTVar m InboundGovernorObservableState
}
-- | Run the server, which consists of the following components:
--
-- * /inbound governor/, it corresponds to p2p-governor on outbound side
-- * /accept loop(s)/, one per given ip address. We support up to one ipv4
-- address and up to one ipv6 address, i.e. an ipv6 enabled node will run two
-- accept loops on listening on different addresses with shared /inbound governor/.
--
-- The server can be run in either of two 'MuxMode'-es:
--
-- * 'InitiatorResponderMode'
-- * 'ResponderMode'
--
-- The first one is used in data diffusion for /Node-To-Node protocol/, while the
-- other is useful for running a server for the /Node-To-Client protocol/.
--
run :: forall muxMode socket peerAddr versionNumber m a b.
( MonadAsync m
, MonadCatch m
, MonadEvaluate m
, MonadLabelledSTM m
, MonadThrow (STM m)
, MonadTime m
, MonadTimer m
, HasResponder muxMode ~ True
, Ord peerAddr
, Show peerAddr
)
=> ServerArguments muxMode socket peerAddr versionNumber ByteString m a b
-> m Void
run ServerArguments {
serverSockets,
serverSnocket,
serverTrTracer,
serverTracer = tracer,
serverInboundGovernorTracer = inboundGovernorTracer,
serverConnectionLimits,
serverInboundIdleTimeout,
serverConnectionManager,
serverControlChannel,
serverObservableStateVar
} = do
let sockets = NonEmpty.toList serverSockets
localAddresses <- traverse (getLocalAddr serverSnocket) sockets
labelTVarIO serverObservableStateVar
( "server-observable-state-"
++ intercalate "-" (show <$> localAddresses)
)
traceWith tracer (TrServerStarted localAddresses)
let threads = (do labelThisThread ( "inbound-governor-"
++ intercalate "-" (show <$> localAddresses)
)
inboundGovernor serverTrTracer
inboundGovernorTracer
serverControlChannel
serverInboundIdleTimeout
serverConnectionManager
serverObservableStateVar)
: [ (accept serverSnocket socket >>= acceptLoop localAddress)
`finally` close serverSnocket socket
| (localAddress, socket) <- localAddresses `zip` sockets
]
raceAll threads
`finally`
traceWith tracer TrServerStopped
`catch`
\(e :: SomeException) -> do
case fromException e of
Just (_ :: AsyncCancelled) -> pure ()
Nothing -> traceWith tracer (TrServerError e)
throwIO e
where
#if !defined(mingw32_HOST_OS)
iseCONNABORTED :: IOError -> Bool
iseCONNABORTED (IOError _ _ _ _ (Just cerrno) _) = eCONNABORTED == Errno cerrno
iseCONNABORTED _ = False
#endif
raceAll :: [m x] -> m x
raceAll [] = error "raceAll: invariant violation"
raceAll [t] = t
raceAll (t : ts) = either id id <$> race t (raceAll ts)
acceptLoop :: peerAddr
-> Accept m socket peerAddr
-> m Void
acceptLoop localAddress acceptOne = do
labelThisThread ("accept-loop-" ++ show localAddress)
runConnectionRateLimits
(TrAcceptPolicyTrace `contramap` tracer)
(numberOfConnections serverConnectionManager)
serverConnectionLimits
result <- runAccept acceptOne
case result of
(AcceptFailure err, acceptNext) -> do
traceWith tracer (TrAcceptError err)
-- Try the determine if the connection was aborted by the remote end
-- before we could process the accept, or if it was a resource
-- exaustion problem.
-- NB. This piece of code is fragile and depends on specific
-- strings/mappings in the network and base libraries.
case fromException err of
Just ioErr ->
#if defined(mingw32_HOST_OS)
-- On Windows the network packet classifies all errors
-- as OtherError. This means that we're forced to match
-- on the error string. The text string comes from
-- the network package's winSockErr.c, and if it ever
-- changes we must update our text string too.
if ioeGetErrorString ioErr /=
"Software caused connection abort (WSAECONNABORTED)"
then throwIO ioErr
else threadDelay 0.5 >>
acceptLoop localAddress acceptNext
#else
if iseCONNABORTED ioErr
then threadDelay 0.5 >> acceptLoop localAddress acceptNext
else throwIO ioErr
#endif
Nothing -> throwIO err
(Accepted socket peerAddr, acceptNext) -> do
traceWith tracer (TrAcceptConnection peerAddr)
-- using withAsync ensures that the thread that includes inbound
-- connection (which is a blocking operation), is killed when the
-- server terminates.
withAsync
(do
a <-
includeInboundConnection
serverConnectionManager
socket peerAddr
case a of
Connected connId dataFlow handle ->
atomically $
ControlChannel.writeMessage
serverControlChannel
(ControlChannel.NewConnection Inbound connId dataFlow handle)
Disconnected {} ->
pure ()
)
$ \_ -> acceptLoop localAddress acceptNext
--
-- Trace
--
data ServerTrace peerAddr
= TrAcceptConnection !peerAddr
| TrAcceptError !SomeException
| TrAcceptPolicyTrace !AcceptConnectionsPolicyTrace
| TrServerStarted ![peerAddr]
| TrServerStopped
| TrServerError !SomeException
-- ^ similar to 'TrAcceptConnection' but it is logged once the connection is
-- handed to inbound connection manager, e.g. after handshake negotiation.
deriving Show