@@ -1,12 +1,3 @@
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE ScopedTypeVariables #-}
4−{-# LANGUAGE RankNTypes #-}
5−{-# LANGUAGE BangPatterns #-}
6−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7−{-# LANGUAGE RecordWildCards #-}
8−{-# LANGUAGE MagicHash #-}
10-- | Local nodes
1-- | Local nodes
12module Control.Distributed.Process.Node
3module Control.Distributed.Process.Node
@@ -21,6 +12,10 @@ module Control.Distributed.Process.Node
22-- TODO: Calls to 'sendBinary' and co (by the NC) may stall the node controller.
13-- TODO: Calls to 'sendBinary' and co (by the NC) may stall the node controller.
15+#if ! MIN_VERSION_base(4,6,0)
16+import Prelude hiding (catch)
24import System.IO (fixIO, hPutStrLn, stderr)
19import System.IO (fixIO, hPutStrLn, stderr)
25import System.Mem.Weak (Weak, deRefWeak)
20import System.Mem.Weak (Weak, deRefWeak)
26import qualified Data.ByteString.Lazy as BSL (fromChunks)
21import qualified Data.ByteString.Lazy as BSL (fromChunks)
@@ -28,67 +23,46 @@ import Data.Binary (decode)
28import Data.Map (Map)
23import Data.Map (Map)
29import qualified Data.Map as Map
24import qualified Data.Map as Map
33 , fromList
27 , fromList
37 , partitionWithKey
29 , partitionWithKey
40 , filterWithKey
31 , filterWithKey
41 , foldlWithKey
32 , foldlWithKey
43−import Data.Time.Format (formatTime)
44−#if MIN_VERSION_time(1,5,0)
45−import Data.Time.Format (defaultTimeLocale)
47−import System.Locale (defaultTimeLocale)
49import Data.Set (Set)
34import Data.Set (Set)
50import qualified Data.Set as Set
35import qualified Data.Set as Set
59import Data.Foldable (forM_)
42import Data.Foldable (forM_)
60import Data.Maybe (isJust, fromJust, isNothing, catMaybes)
43import Data.Maybe (isJust, fromJust, isNothing, catMaybes)
61import Data.Typeable (Typeable)
44import Data.Typeable (Typeable)
62import Control.Category ((>>>))
45import Control.Category ((>>>))
63−import Control.Applicative
46+import Control.Applicative ((<$>))
64−import Control.Monad (void, when, join)
47+import Control.Monad (void, when)
65import Control.Monad.IO.Class (MonadIO, liftIO)
48import Control.Monad.IO.Class (MonadIO, liftIO)
66import Control.Monad.State.Strict (MonadState, StateT, evalStateT, gets)
49import Control.Monad.State.Strict (MonadState, StateT, evalStateT, gets)
67import qualified Control.Monad.State.Strict as StateT (get, put)
50import qualified Control.Monad.State.Strict as StateT (get, put)
68import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask)
51import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask)
69import Control.Exception
52import Control.Exception
54+ , AsyncException(ThreadKilled)
71 , SomeException
55 , SomeException
72 , Exception
56 , Exception
74− , uninterruptibleMask_
78−import qualified Control.Exception as Exception
59+import qualified Control.Exception as Exception (Handler(..), catch, catches, finally)
84−import Control.Concurrent (forkIO, killThread)
60+import Control.Concurrent (forkIO, myThreadId)
85−import Control.Distributed.Process.Internal.BiMultiMap (BiMultiMap)
86−import qualified Control.Distributed.Process.Internal.BiMultiMap as BiMultiMap
87import Control.Distributed.Process.Internal.StrictMVar
61import Control.Distributed.Process.Internal.StrictMVar
89 , withMVar
63 , withMVar
91 , modifyMVar
64 , modifyMVar
92 , newEmptyMVar
66 , newEmptyMVar
94 , takeMVar
68 , takeMVar
@@ -103,7 +77,6 @@ import Control.Distributed.Process.Internal.CQueue
103 , enqueue
77 , enqueue
104 , newCQueue
78 , newCQueue
105 , mkWeakCQueue
79 , mkWeakCQueue
108import qualified Network.Transport as NT
81import qualified Network.Transport as NT
109 ( Transport
82 ( Transport
@@ -115,8 +88,8 @@ import qualified Network.Transport as NT
115 , TransportError(..)
88 , TransportError(..)
116 , address
89 , address
117 , closeEndPoint
90 , closeEndPoint
119 , ConnectionId
91 , ConnectionId
121 , EndPointAddress
94 , EndPointAddress
122 , Reliability(ReliableOrdered)
95 , Reliability(ReliableOrdered)
@@ -133,11 +106,8 @@ import Control.Distributed.Process.Internal.Types
133 , LocalProcessId(..)
106 , LocalProcessId(..)
134 , ProcessId(..)
107 , ProcessId(..)
135 , LocalNode(..)
108 , LocalNode(..)
136− , MxEventBus(..)
109+ , Tracer(..)
137 , LocalNodeState(..)
110 , LocalNodeState(..)
138− , ValidLocalNodeState(..)
139− , withValidLocalState
140− , modifyValidLocalState
141 , LocalProcess(..)
111 , LocalProcess(..)
142 , LocalProcessState(..)
112 , LocalProcessState(..)
143 , Process(..)
113 , Process(..)
@@ -147,11 +117,9 @@ import Control.Distributed.Process.Internal.Types
147 , localPidCounter
117 , localPidCounter
148 , localPidUnique
118 , localPidUnique
149 , localProcessWithId
119 , localProcessWithId
151 , localConnections
120 , localConnections
152 , forever'
121 , forever'
153 , MonitorRef(..)
122 , MonitorRef(..)
154− , NodeClosedException(..)
155 , ProcessMonitorNotification(..)
123 , ProcessMonitorNotification(..)
156 , NodeMonitorNotification(..)
124 , NodeMonitorNotification(..)
157 , PortMonitorNotification(..)
125 , PortMonitorNotification(..)
@@ -171,74 +139,55 @@ import Control.Distributed.Process.Internal.Types
172 , ProcessInfo(..)
140 , ProcessInfo(..)
173 , ProcessInfoNone(..)
141 , ProcessInfoNone(..)
175 , SendPortId(..)
142 , SendPortId(..)
176 , typedChannelWithId
143 , typedChannelWithId
177 , RegisterReply(..)
144 , RegisterReply(..)
178 , WhereIsReply(..)
145 , WhereIsReply(..)
179 , payloadToMessage
146 , payloadToMessage
180 , createUnencodedMessage
147 , createUnencodedMessage
181− , unsafeCreateUnencodedMessage
182 , runLocalProcess
148 , runLocalProcess
183 , firstNonReservedProcessId
149 , firstNonReservedProcessId
184 , ImplicitReconnect(WithImplicitReconnect)
150 , ImplicitReconnect(WithImplicitReconnect)
186−import Control.Distributed.Process.Management.Internal.Agent
189−import Control.Distributed.Process.Management.Internal.Types
192−import qualified Control.Distributed.Process.Management.Internal.Trace.Remote as Trace
152+import qualified Control.Distributed.Process.Internal.Trace.Remote as Trace
193 ( remoteTable
153 ( remoteTable
195−import Control.Distributed.Process.Management.Internal.Trace.Tracer
155+import Control.Distributed.Process.Internal.Trace.Types
198−import Control.Distributed.Process.Management.Internal.Trace.Types
199 ( TraceArg(..)
156 ( TraceArg(..)
200 , traceEvent
158 , traceEvent
201 , traceLogFmt
159 , traceLogFmt
202 , enableTrace
160 , enableTrace
162+import Control.Distributed.Process.Internal.Trace.Tracer
204import Control.Distributed.Process.Serializable (Serializable)
166import Control.Distributed.Process.Serializable (Serializable)
205import Control.Distributed.Process.Internal.Messaging
167import Control.Distributed.Process.Internal.Messaging
206 ( sendBinary
168 ( sendBinary
207 , closeImplicitReconnections
170 , closeImplicitReconnections
208 , impliesDeathOf
171 , impliesDeathOf
210import Control.Distributed.Process.Internal.Primitives
173import Control.Distributed.Process.Internal.Primitives
211 ( register
174 ( register
212 , receiveWait
176 , receiveWait
214 , sendChan
178 , sendChan
215 , unwrapMessage
180 , unwrapMessage
221−import Control.Distributed.Process.Internal.Types (SendPort, Tracer(..))
182+import Control.Distributed.Process.Internal.Types (SendPort)
222import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
183import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
223import Control.Distributed.Process.Internal.WeakTQueue (TQueue, writeTQueue)
184import Control.Distributed.Process.Internal.WeakTQueue (TQueue, writeTQueue)
224import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
185import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
225 ( mapMaybe
186 ( mapMaybe
226 , mapDefault
187 , mapDefault
228−import Control.Monad.Catch (try)
189+import System.Environment (getEnv)
229−import GHC.IO (IO(..), unsafeUnmask)
230−import GHC.Base ( maskAsyncExceptions# )
232import Unsafe.Coerce
190import Unsafe.Coerce
235−-- Remove these definitions when the fix for
236−-- https://ghc.haskell.org/trac/ghc/ticket/10149
237−-- is included in all supported compilers:
238−block :: IO a -> IO a
239−block (IO io) = IO $ maskAsyncExceptions# io
240−unblock :: IO a -> IO a
241−unblock = unsafeUnmask
243--------------------------------------------------------------------------------
192--------------------------------------------------------------------------------
244-- Initialization --
193-- Initialization --
@@ -262,7 +211,7 @@ newLocalNode transport rtable = do
262createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
211createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
263createBareLocalNode endPoint rtable = do
212createBareLocalNode endPoint rtable = do
264 unq <- randomIO
213 unq <- randomIO
265− state <- newMVar $ LocalNodeValid $ ValidLocalNodeState
214+ state <- newMVar LocalNodeState
266 { _localProcesses = Map.empty
215 { _localProcesses = Map.empty
267 , _localPidCounter = firstNonReservedProcessId
216 , _localPidCounter = firstNonReservedProcessId
268 , _localPidUnique = unq
217 , _localPidUnique = unq
@@ -273,10 +222,10 @@ createBareLocalNode endPoint rtable = do
273 , localEndPoint = endPoint
222 , localEndPoint = endPoint
274 , localState = state
223 , localState = state
275 , localCtrlChan = ctrlChan
224 , localCtrlChan = ctrlChan
276− , localEventBus = MxEventBusInitialising
225+ , localTracer = InactiveTracer
277 , remoteTable = rtable
226 , remoteTable = rtable
279− tracedNode <- startMxAgent node
228+ tracedNode <- startTracing node
281 -- Once the NC terminates, the endpoint isn't much use,
230 -- Once the NC terminates, the endpoint isn't much use,
282 void $ forkIO $ Exception.finally (runNodeController tracedNode)
231 void $ forkIO $ Exception.finally (runNodeController tracedNode)
@@ -294,27 +243,38 @@ createBareLocalNode endPoint rtable = do
294 , ctrlMsgSignal = SigShutdown
243 , ctrlMsgSignal = SigShutdown
297−startMxAgent :: LocalNode -> IO LocalNode
246+startTracing :: LocalNode -> IO LocalNode
298−startMxAgent node = do
247+startTracing node =
248+ -- TODO: use tryGetEnv once we drop support for GHC 7.2.x
250+ (getEnv "DISTRIBUTED_PROCESS_TRACE_ENABLED" >> procTracer node)
251+ (\(_ :: IOError) -> return node)
252+ where procTracer :: LocalNode -> IO LocalNode
299− -- see note [tracer/forkProcess races]
254+ -- see note [tracer/forkProcess races]
300− let fork = forkProcess node
301− mv <- MVar.newEmptyMVar
255+ mv <- MVar.newEmptyMVar
302− pid <- fork $ mxAgentController fork mv
256+ pid <- forkProcess n (traceController mv)
303− (tracer', wqRef, mxNew') <- MVar.takeMVar mv
257+ wqRef <- MVar.takeMVar mv
304− return node { localEventBus = (MxEventBus pid tracer' wqRef mxNew') }
258+ return n { localTracer = (ActiveTracer pid wqRef) }
306−startDefaultTracer :: LocalNode -> IO ()
260+startDefaultTracer :: LocalNode -> IO (Maybe ProcessId)
307−startDefaultTracer node' = do
261+startDefaultTracer node =
308− let t = localEventBus node'
262+ Exception.catch
263+ (getEnv "DISTRIBUTED_PROCESS_TRACE_ENABLED" >> go node)
264+ (\(_ :: IOError) -> return Nothing)
265+ where go :: LocalNode -> IO (Maybe ProcessId)
267+ registerTraceController node'
268+ pid <- forkProcess node' defaultTracer
269+ enableTrace (localTracer node') pid
272+ registerTraceController :: LocalNode -> IO ()
273+ registerTraceController n =
274+ let t = localTracer n in
309− case t of
275+ case t of
310− MxEventBus _ (Tracer pid _) _ _ -> do
276+ InactiveTracer -> return ()
311− runProcess node' $ register "trace.controller" pid
277+ (ActiveTracer pid _) -> runProcess n $ register "trace.controller" pid
312− pid' <- forkProcess node' defaultTracer
313− enableTrace (localEventBus node') pid'
314− runProcess node' $ register "tracer.initial" pid'
317−-- TODO: we need a better mechanism for defining and registering services
319-- | Start and register the service processes on a node
279-- | Start and register the service processes on a node
320startServiceProcesses :: LocalNode -> IO ()
280startServiceProcesses :: LocalNode -> IO ()
@@ -323,71 +283,53 @@ startServiceProcesses node = do
323 -- the default tracer first, even though it might @nsend@ to the logger
283 -- the default tracer first, even though it might @nsend@ to the logger
324 -- before /that/ process has started - this is a totally harmless race
284 -- before /that/ process has started - this is a totally harmless race
325 -- however, so we deliberably ignore it
285 -- however, so we deliberably ignore it
326− startDefaultTracer node
286+ mPid <- startDefaultTracer node
288+ Nothing -> return ()
289+ Just pid -> runProcess node $ register "tracer.initial" pid
327 logger <- forkProcess node loop
291 logger <- forkProcess node loop
328− runProcess node $ do
329− register "logger" logger
330− -- The trace.logger is used for tracing to the console to avoid feedback
331− -- loops during tracing if the user reregisters the "logger" with a custom
332− -- process which uses 'send' or other primitives which are traced.
333− register "trace.logger" logger
292+ runProcess node $ register "logger" logger
335− loop = do
294+ loop = do
336− receiveWait
295+ receiveWait
337− [ match $ \(SayMessage time pid string) -> do
296+ [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
338− let time' = formatTime defaultTimeLocale "%c" time
339− liftIO . hPutStrLn stderr $ time' ++ " " ++ show pid ++ ": " ++ string
297+ liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
341− , match $ \((time, string) :: (String, String)) -> do
299+ , match $ \((time, string) :: (String, String)) -> do
342− -- this is a 'trace' message from the local node tracer
300+ -- this is a 'trace' message from the local node tracer
343− liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
301+ liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
345− , match $ \(ch :: SendPort ()) -> -- a shutdown request
303+ , match $ \(ch :: SendPort ()) -> -- a shutdown request
346− sendChan ch ()
304+ sendChan ch ()
349−-- | Force-close a local node, killing all processes on that node.
307+-- | Force-close a local node
309+-- TODO: for now we just close the associated endpoint
350closeLocalNode :: LocalNode -> IO ()
310closeLocalNode :: LocalNode -> IO ()
351−closeLocalNode node = do
311+closeLocalNode node =
352− -- Kill processes after refilling the mvar. Otherwise, there is potential for
312+ -- TODO: close all our processes, surely!?
353− -- deadlock as a dying process tries to get the mvar while masking exceptions
355− join $ modifyMVar (localState node) $ \st -> case st of
356− LocalNodeValid vst -> do
357− return ( LocalNodeClosed
358− , forM_ (vst ^. localProcesses) $ \lproc ->
359− -- Semantics of 'throwTo' guarantee that target thread will get
360− -- delivered an exception. Therefore, target thread will be
361− -- killed eventually and that's as good as we can do. No need
362− -- to wait for thread to actually finish dying.
363− killThread (processThread lproc)
365− LocalNodeClosed -> return (LocalNodeClosed, return ())
366− -- This call will have the effect of shutting down the NC as well (see
367− -- 'createBareLocalNode').
368 NT.closeEndPoint (localEndPoint node)
313 NT.closeEndPoint (localEndPoint node)
370-- | Run a process on a local node and wait for it to finish
315-- | Run a process on a local node and wait for it to finish
371runProcess :: LocalNode -> Process () -> IO ()
316runProcess :: LocalNode -> Process () -> IO ()
372runProcess node proc = do
317runProcess node proc = do
373 done <- newEmptyMVar
318 done <- newEmptyMVar
374− -- TODO; When forkProcess inherits the masking state, protect the forked
319+ tid <- myThreadId
375− -- thread against async exceptions that could occur before 'try' is evaluated.
376− void $ forkProcess node $ try proc >>= liftIO . putMVar done
320+ void $ forkProcess node $ do
377− takeMVar done >>= either (throwIO :: SomeException -> IO a) return
321+ catch (proc `finally` liftIO (putMVar done ()))
322+ (\(ex :: SomeException) -> liftIO $ throwTo tid ex)
379-- | Spawn a new process on a local node
325-- | Spawn a new process on a local node
380forkProcess :: LocalNode -> Process () -> IO ProcessId
326forkProcess :: LocalNode -> Process () -> IO ProcessId
381−forkProcess node proc = do
382− ms <- getMaskingState
383− modifyMVarMasked (localState node) (startProcess ms)
327+forkProcess node proc = modifyMVar (localState node) startProcess
385− startProcess :: MaskingState
387− -> IO (LocalNodeState, ProcessId)
329+ startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
388− startProcess ms (LocalNodeValid vst) = do
330+ startProcess st = do
389− let lpid = LocalProcessId { lpidCounter = vst ^. localPidCounter
331+ let lpid = LocalProcessId { lpidCounter = st ^. localPidCounter
390− , lpidUnique = vst ^. localPidUnique
332+ , lpidUnique = st ^. localPidUnique
392 let pid = ProcessId { processNodeId = localNodeId node
334 let pid = ProcessId { processNodeId = localNodeId node
393 , processLocalId = lpid
335 , processLocalId = lpid
@@ -407,15 +349,9 @@ forkProcess node proc = do
407 , processThread = tid
349 , processThread = tid
408 , processNode = node
350 , processNode = node
410− -- Rewrite this code when this is fixed:
411− -- https://ghc.haskell.org/trac/ghc/ticket/10149
412− let unmask = case ms of
414− MaskedInterruptible -> block
415− MaskedUninterruptible -> id
416− tid' <- uninterruptibleMask_ $ forkIO $ do
352+ tid' <- forkIO $ do
417 reason <- Exception.catches
353 reason <- Exception.catches
418− (unmask $ runLocalProcess lproc proc >> return DiedNormal)
354+ (runLocalProcess lproc proc >> return DiedNormal)
419 [ (Exception.Handler (\ex@(ProcessExitException from msg) -> do
355 [ (Exception.Handler (\ex@(ProcessExitException from msg) -> do
420 mMsg <- unwrapMessage msg :: IO (Maybe String)
356 mMsg <- unwrapMessage msg :: IO (Maybe String)
421 case mMsg of
357 case mMsg of
@@ -425,60 +361,47 @@ forkProcess node proc = do
425 (return . DiedException . (show :: SomeException -> String)))]
361 (return . DiedException . (show :: SomeException -> String)))]
427 -- [Unified: Table 4, rules termination and exiting]
363 -- [Unified: Table 4, rules termination and exiting]
428− mconns <- modifyValidLocalState node (cleanupProcess pid)
364+ modifyMVar_ (localState node) (cleanupProcess pid)
429− -- XXX: Revisit after agreeing on the bigger picture for the semantics
430− -- of transport operations.
431− -- https://github.com/haskell-distributed/distributed-process/issues/204
432− forM_ mconns $ forkIO . mapM_ NT.close
434 writeChan (localCtrlChan node) NCMsg
365 writeChan (localCtrlChan node) NCMsg
435 { ctrlMsgSender = ProcessIdentifier pid
366 { ctrlMsgSender = ProcessIdentifier pid
436 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
367 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
438 return (tid', lproc)
369 return (tid', lproc)
440 -- see note [tracer/forkProcess races]
372 -- see note [tracer/forkProcess races]
441− trace node (MxSpawned pid)
373+ trace node (TraceEvSpawned pid)
443 if lpidCounter lpid == maxBound
375 if lpidCounter lpid == maxBound
445− -- TODO: this doesn't look right at all - how do we know
446− -- that newUnique represents a process id that is available!?
447 newUnique <- randomIO
377 newUnique <- randomIO
448− return ( LocalNodeValid
449− $ (localProcessWithId lpid ^= Just lproc)
378+ return ( (localProcessWithId lpid ^= Just lproc)
450 . (localPidCounter ^= firstNonReservedProcessId)
379 . (localPidCounter ^= firstNonReservedProcessId)
451 . (localPidUnique ^= newUnique)
380 . (localPidUnique ^= newUnique)
456− return ( LocalNodeValid
457− $ (localProcessWithId lpid ^= Just lproc)
385+ return ( (localProcessWithId lpid ^= Just lproc)
458 . (localPidCounter ^: (+ 1))
386 . (localPidCounter ^: (+ 1))
462− startProcess _ LocalNodeClosed =
463− throwIO $ NodeClosedException $ localNodeId node
465− cleanupProcess :: ProcessId
391+ cleanupProcess :: ProcessId -> LocalNodeState -> IO LocalNodeState
466− -> ValidLocalNodeState
467− -> IO (ValidLocalNodeState, [NT.Connection])
468− cleanupProcess pid vst = do
392+ cleanupProcess pid st = do
469 let pid' = ProcessIdentifier pid
393 let pid' = ProcessIdentifier pid
470− let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (vst ^. localConnections)
394+ let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (st ^. localConnections)
395+ mapM_ (NT.close . fst) (Map.elems affected)
471− return ( (localProcessWithId (processLocalId pid) ^= Nothing)
396+ return $ (localProcessWithId (processLocalId pid) ^= Nothing)
472− . (localConnections ^= unaffected)
397+ . (localConnections ^= unaffected)
474− , map fst $ Map.elems affected
477-- note [tracer/forkProcess races]
400-- note [tracer/forkProcess races]
479-- Our startTracing function uses forkProcess to start the trace controller
402-- Our startTracing function uses forkProcess to start the trace controller
480-- process, and of course forkProcess attempts to call traceEvent once the
403-- process, and of course forkProcess attempts to call traceEvent once the
481−-- process has started. This is harmless, as the localEventBus is not updated
404+-- process has started. This is harmless, as the localTracer is not updated
482-- until /after/ the initial forkProcess completes, so the first call to
405-- until /after/ the initial forkProcess completes, so the first call to
483-- traceEvent behaves as if tracing were disabled (i.e., it is ignored).
406-- traceEvent behaves as if tracing were disabled (i.e., it is ignored).
@@ -492,7 +415,7 @@ type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
492data IncomingTarget =
415data IncomingTarget =
494 | ToProc ProcessId (Weak (CQueue Message))
417 | ToProc ProcessId (Weak (CQueue Message))
495− | ToChan SendPortId TypedChannel
418+ | ToChan TypedChannel
498data ConnectionState = ConnectionState {
421data ConnectionState = ConnectionState {
@@ -519,7 +442,6 @@ incomingFrom addr = aux >>> DAC.mapDefault Set.empty addr
520handleIncomingMessages :: LocalNode -> IO ()
443handleIncomingMessages :: LocalNode -> IO ()
521handleIncomingMessages node = go initConnectionState
444handleIncomingMessages node = go initConnectionState
522− `Exception.catch` \(NodeClosedException _) -> return ()
524 go :: ConnectionState -> IO ()
446 go :: ConnectionState -> IO ()
525 go !st = do
447 go !st = do
@@ -528,14 +450,13 @@ handleIncomingMessages node = go initConnectionState
528 NT.ConnectionOpened cid rel theirAddr ->
450 NT.ConnectionOpened cid rel theirAddr ->
529 if rel == NT.ReliableOrdered
451 if rel == NT.ReliableOrdered
531− trace node (MxConnected cid theirAddr)
453+ trace node (TraceEvConnected cid)
533 (incomingAt cid ^= Just (theirAddr, Uninit))
455 (incomingAt cid ^= Just (theirAddr, Uninit))
534 . (incomingFrom theirAddr ^: Set.insert cid)
456 . (incomingFrom theirAddr ^: Set.insert cid)
537− else invalidRequest cid st $
459+ else invalidRequest cid st
538− "attempt to connect with unsupported reliability " ++ show rel
539 NT.Received cid payload ->
460 NT.Received cid payload ->
540 case st ^. incomingAt cid of
461 case st ^. incomingAt cid of
541 Just (_, ToProc pid weakQueue) -> do
462 Just (_, ToProc pid weakQueue) -> do
@@ -545,19 +466,15 @@ handleIncomingMessages node = go initConnectionState
545 -- it from the NC state? (and same for channels, below)
466 -- it from the NC state? (and same for channels, below)
546 let msg = payloadToMessage payload
467 let msg = payloadToMessage payload
547 enqueue queue msg -- 'enqueue' is strict
468 enqueue queue msg -- 'enqueue' is strict
548− trace node (MxReceived pid msg)
469+ trace node (TraceEvReceived pid msg)
550− Just (_, ToChan chId (TypedChannel chan')) -> do
471+ Just (_, ToChan (TypedChannel chan')) -> do
551 mChan <- deRefWeak chan'
472 mChan <- deRefWeak chan'
552 -- If mChan is Nothing, the process has given up the read end of
473 -- If mChan is Nothing, the process has given up the read end of
553 -- the channel and we simply ignore the incoming message
474 -- the channel and we simply ignore the incoming message
554− forM_ mChan $ \chan -> do
475+ forM_ mChan $ \chan -> atomically $
555− msg' <- atomically $ do
556− msg <- return $! decode (BSL.fromChunks payload)
557− -- We make sure the message is fully decoded when it is enqueued
476+ -- We make sure the message is fully decoded when it is enqueued
558− writeTQueue chan msg
477+ writeTQueue chan $! decode (BSL.fromChunks payload)
560− trace node $ MxReceivedPort chId $ unsafeCreateUnencodedMessage msg'
562 Just (_, ToNode) -> do
479 Just (_, ToNode) -> do
563 let ctrlMsg = decode . BSL.fromChunks $ payload
480 let ctrlMsg = decode . BSL.fromChunks $ payload
@@ -567,49 +484,38 @@ handleIncomingMessages node = go initConnectionState
567 case decode (BSL.fromChunks payload) of
484 case decode (BSL.fromChunks payload) of
568 ProcessIdentifier pid -> do
485 ProcessIdentifier pid -> do
569 let lpid = processLocalId pid
486 let lpid = processLocalId pid
570− mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
487+ mProc <- withMVar state $ return . (^. localProcessWithId lpid)
571 case mProc of
488 case mProc of
572 Just proc ->
489 Just proc ->
573 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
490 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
574 Nothing ->
491 Nothing ->
575− -- incoming attempt to connect to unknown process - might
492+ invalidRequest cid st
577− go (incomingAt cid ^= Nothing $ st)
578 SendPortIdentifier chId -> do
493 SendPortIdentifier chId -> do
579 let lcid = sendPortLocalId chId
494 let lcid = sendPortLocalId chId
580 lpid = processLocalId (sendPortProcessId chId)
495 lpid = processLocalId (sendPortProcessId chId)
581− mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
496+ mProc <- withMVar state $ return . (^. localProcessWithId lpid)
582 case mProc of
497 case mProc of
583 Just proc -> do
498 Just proc -> do
584 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
499 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
585 case mChannel of
500 case mChannel of
586 Just channel ->
501 Just channel ->
587− go (incomingAt cid ^= Just (src, ToChan chId channel) $ st)
502+ go (incomingAt cid ^= Just (src, ToChan channel) $ st)
588 Nothing ->
503 Nothing ->
589− invalidRequest cid st $
504+ invalidRequest cid st
590− "incoming attempt to connect to unknown channel of"
591− ++ " process " ++ show (sendPortProcessId chId)
592 Nothing ->
505 Nothing ->
593− -- incoming attempt to connect to channel of unknown
506+ invalidRequest cid st
594− -- process - might be dead already
595− go (incomingAt cid ^= Nothing $ st)
596 NodeIdentifier nid ->
507 NodeIdentifier nid ->
597 if nid == localNodeId node
508 if nid == localNodeId node
598 then go (incomingAt cid ^= Just (src, ToNode) $ st)
509 then go (incomingAt cid ^= Just (src, ToNode) $ st)
599− else invalidRequest cid st $
510+ else invalidRequest cid st
600− "incoming attempt to connect to a different node -"
601− ++ " I'm " ++ show (localNodeId node)
602− ++ " but the remote peer wants to connect to "
604 Nothing ->
511 Nothing ->
605 invalidRequest cid st
512 invalidRequest cid st
606− "message received from an unknown connection"
607 NT.ConnectionClosed cid ->
513 NT.ConnectionClosed cid ->
608 case st ^. incomingAt cid of
514 case st ^. incomingAt cid of
609 Nothing ->
515 Nothing ->
610− invalidRequest cid st "closed unknown connection"
516+ invalidRequest cid st
611 Just (src, _) -> do
517 Just (src, _) -> do
612− trace node (MxDisconnected cid src)
518+ trace node (TraceEvDisconnected cid)
613 go ( (incomingAt cid ^= Nothing)
519 go ( (incomingAt cid ^= Nothing)
614 . (incomingFrom src ^: Set.delete cid)
520 . (incomingFrom src ^: Set.delete cid)
@@ -638,20 +544,19 @@ handleIncomingMessages node = go initConnectionState
638 -- and we just give up
544 -- and we just give up
639 fail "Cloud Haskell fatal error: received unexpected multicast"
545 fail "Cloud Haskell fatal error: received unexpected multicast"
641− invalidRequest :: NT.ConnectionId -> ConnectionState -> String -> IO ()
547+ invalidRequest :: NT.ConnectionId -> ConnectionState -> IO ()
642− invalidRequest cid st msg = do
548+ invalidRequest cid st = do
643 -- TODO: We should treat this as a fatal error on the part of the remote
549 -- TODO: We should treat this as a fatal error on the part of the remote
644 -- node. That is, we should report the remote node as having died, and we
550 -- node. That is, we should report the remote node as having died, and we
645 -- should close incoming connections (this requires a Transport layer
551 -- should close incoming connections (this requires a Transport layer
646 -- extension).
552 -- extension).
647− traceEventFmtIO node "" [ TraceStr $ " [network] invalid request"
553+ traceEventFmtIO node "" [(TraceStr " [network] invalid request: "),
648− ++ " (" ++ msg ++ "): "
649− , (Trace cid)
554+ (Trace cid)]
651 go ( incomingAt cid ^= Nothing
555 go ( incomingAt cid ^= Nothing
559+ state = localState node
655 endpoint = localEndPoint node
560 endpoint = localEndPoint node
656 ctrlChan = localCtrlChan node
561 ctrlChan = localCtrlChan node
@@ -660,9 +565,8 @@ handleIncomingMessages node = go initConnectionState
660--------------------------------------------------------------------------------
565--------------------------------------------------------------------------------
662runNodeController :: LocalNode -> IO ()
567runNodeController :: LocalNode -> IO ()
663−runNodeController node =
568+runNodeController =
664− runReaderT (evalStateT (unNC nodeController) initNCState) node
569+ runReaderT (evalStateT (unNC nodeController) initNCState)
665− `Exception.catch` \(NodeClosedException _) -> return ()
667--------------------------------------------------------------------------------
571--------------------------------------------------------------------------------
668-- Internal data types --
572-- Internal data types --
@@ -670,26 +574,20 @@ runNodeController node =
671data NCState = NCState
575data NCState = NCState
672 { -- Mapping from remote processes to linked local processes
576 { -- Mapping from remote processes to linked local processes
673− _links :: !(BiMultiMap Identifier ProcessId ())
577+ _links :: !(Map Identifier (Set ProcessId))
674 -- Mapping from remote processes to monitoring local processes
578 -- Mapping from remote processes to monitoring local processes
675− , _monitors :: !(BiMultiMap Identifier ProcessId MonitorRef)
579+ , _monitors :: !(Map Identifier (Set (ProcessId, MonitorRef)))
676 -- Process registry: names and where they live, mapped to the PIDs
580 -- Process registry: names and where they live, mapped to the PIDs
677 , _registeredHere :: !(Map String ProcessId)
581 , _registeredHere :: !(Map String ProcessId)
678 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
582 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
681newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
585newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
682− deriving ( Applicative
686− , MonadState NCState
687− , MonadReader LocalNode
586+ deriving (Functor, Monad, MonadIO, MonadState NCState, MonadReader LocalNode)
690initNCState :: NCState
588initNCState :: NCState
691−initNCState = NCState { _links = BiMultiMap.empty
589+initNCState = NCState { _links = Map.empty
692− , _monitors = BiMultiMap.empty
590+ , _monitors = Map.empty
693 , _registeredHere = Map.empty
591 , _registeredHere = Map.empty
694 , _registeredOnNodes = Map.empty
592 , _registeredOnNodes = Map.empty
@@ -705,46 +603,19 @@ instance Show ProcessKillException where
705 show (ProcessKillException pid reason) =
603 show (ProcessKillException pid reason) =
706 "killed-by=" ++ show pid ++ ",reason=" ++ reason
604 "killed-by=" ++ show pid ++ ",reason=" ++ reason
708−ncSendToProcess :: ProcessId -> Message -> NC ()
709−ncSendToProcess = ncSendToProcessAndTrace True
711−ncSendToProcessAndTrace :: Bool -> ProcessId -> Message -> NC ()
712−ncSendToProcessAndTrace shouldTrace pid msg = do
714− if processNodeId pid == localNodeId node
715− then ncEffectLocalSendAndTrace shouldTrace node pid msg
716− else liftIO $ sendBinary node
717− (NodeIdentifier $ localNodeId node)
718− (NodeIdentifier $ processNodeId pid)
719− WithImplicitReconnect
720− NCMsg { ctrlMsgSender = NodeIdentifier $ localNodeId node
721− , ctrlMsgSignal = UnreliableSend (processLocalId pid) msg
724−ncSendToNode :: NodeId -> NCMsg -> NC ()
725−ncSendToNode to msg = do
727− liftIO $ if to == localNodeId node
728− then writeChan (localCtrlChan node) $! msg
729− else sendBinary node
730− (NodeIdentifier $ localNodeId node)
732− WithImplicitReconnect
735--------------------------------------------------------------------------------
606--------------------------------------------------------------------------------
736-- Tracing/Debugging --
607-- Tracing/Debugging --
737--------------------------------------------------------------------------------
608--------------------------------------------------------------------------------
739−-- [Issue #104 / DP-13]
610+-- [Issue #104]
741traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
612traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
742traceNotifyDied node ident reason =
613traceNotifyDied node ident reason =
743 -- TODO: sendPortDied notifications
614 -- TODO: sendPortDied notifications
744 liftIO $ withLocalTracer node $ \t ->
615 liftIO $ withLocalTracer node $ \t ->
745 case ident of
616 case ident of
746− (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
617+ (NodeIdentifier nid) -> traceEvent t (TraceEvNodeDied nid reason)
747− (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
618+ (ProcessIdentifier pid) -> traceEvent t (TraceEvDied pid reason)
748 _ -> return ()
619 _ -> return ()
750traceEventFmtIO :: LocalNode
621traceEventFmtIO :: LocalNode
@@ -754,11 +625,11 @@ traceEventFmtIO :: LocalNode
754traceEventFmtIO node fmt args =
625traceEventFmtIO node fmt args =
755 withLocalTracer node $ \t -> traceLogFmt t fmt args
626 withLocalTracer node $ \t -> traceLogFmt t fmt args
757−trace :: LocalNode -> MxEvent -> IO ()
628+trace :: LocalNode -> TraceEvent -> IO ()
758trace node ev = withLocalTracer node $ \t -> traceEvent t ev
629trace node ev = withLocalTracer node $ \t -> traceEvent t ev
760−withLocalTracer :: LocalNode -> (MxEventBus -> IO ()) -> IO ()
631+withLocalTracer :: LocalNode -> (Tracer -> IO ()) -> IO ()
761−withLocalTracer node act = act (localEventBus node)
632+withLocalTracer node act = act (localTracer node)
763--------------------------------------------------------------------------------
634--------------------------------------------------------------------------------
764-- Core functionality --
635-- Core functionality --
@@ -774,7 +645,11 @@ nodeController = do
774 -- [Unified: Table 7, rule nc_forward]
645 -- [Unified: Table 7, rule nc_forward]
775 case destNid (ctrlMsgSignal msg) of
646 case destNid (ctrlMsgSignal msg) of
776 Just nid' | nid' /= localNodeId node ->
647 Just nid' | nid' /= localNodeId node ->
777− ncSendToNode nid' msg
648+ liftIO $ sendBinary node
650+ (NodeIdentifier nid')
651+ WithImplicitReconnect
779 return ()
654 return ()
@@ -797,8 +672,6 @@ nodeController = do
797 ncEffectWhereIs from label
672 ncEffectWhereIs from label
798 NCMsg _ (NamedSend label msg') ->
673 NCMsg _ (NamedSend label msg') ->
799 ncEffectNamedSend label msg'
674 ncEffectNamedSend label msg'
800− NCMsg _ (UnreliableSend lpid msg') ->
801− ncEffectLocalSend node (ProcessId (localNodeId node) lpid) msg'
802 NCMsg _ (LocalSend to msg') ->
675 NCMsg _ (LocalSend to msg') ->
803 ncEffectLocalSend node to msg'
676 ncEffectLocalSend node to msg'
804 NCMsg _ (LocalPortSend to msg') ->
677 NCMsg _ (LocalPortSend to msg') ->
@@ -812,9 +685,8 @@ nodeController = do
812 NCMsg _ SigShutdown ->
685 NCMsg _ SigShutdown ->
813 liftIO $ do
686 liftIO $ do
814 NT.closeEndPoint (localEndPoint node)
687 NT.closeEndPoint (localEndPoint node)
815− `Exception.finally` throwIO (NodeClosedException $ localNodeId node)
688+ `Exception.finally` throwIO ThreadKilled
816− NCMsg (ProcessIdentifier from) (GetNodeStats nid) ->
689+ -- ThreadKilled seems to make more sense than fail/error here
817− ncEffectGetNodeStats from nid
818 unexpected ->
690 unexpected ->
819 error $ "nodeController: unexpected message " ++ show unexpected
691 error $ "nodeController: unexpected message " ++ show unexpected
@@ -832,18 +704,22 @@ ncEffectMonitor from them mRef = do
832 case (shouldLink, isLocal node (ProcessIdentifier from)) of
704 case (shouldLink, isLocal node (ProcessIdentifier from)) of
833 (True, _) -> -- [Unified: first rule]
705 (True, _) -> -- [Unified: first rule]
834 case mRef of
706 case mRef of
835− Just ref -> modify' $ monitors ^: BiMultiMap.insert them from ref
707+ Just ref -> modify' $ monitorsFor them ^: Set.insert (from, ref)
836− Nothing -> modify' $ links ^: BiMultiMap.insert them from ()
708+ Nothing -> modify' $ linksFor them ^: Set.insert from
837 (False, True) -> -- [Unified: second rule]
709 (False, True) -> -- [Unified: second rule]
838 notifyDied from them DiedUnknownId mRef
710 notifyDied from them DiedUnknownId mRef
839 (False, False) -> -- [Unified: third rule]
711 (False, False) -> -- [Unified: third rule]
840 -- TODO: this is the right sender according to the Unified semantics,
712 -- TODO: this is the right sender according to the Unified semantics,
841 -- but perhaps having 'them' as the sender would make more sense
713 -- but perhaps having 'them' as the sender would make more sense
842 -- (see also: notifyDied)
714 -- (see also: notifyDied)
715+ liftIO $ sendBinary node
716+ (NodeIdentifier $ localNodeId node)
843− ncSendToNode (processNodeId from) $ NCMsg
717+ (NodeIdentifier $ processNodeId from)
718+ WithImplicitReconnect
844− { ctrlMsgSender = NodeIdentifier (localNodeId node)
720+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
845− , ctrlMsgSignal = Died them DiedUnknownId
721+ , ctrlMsgSignal = Died them DiedUnknownId
848-- [Unified: Table 11]
724-- [Unified: Table 11]
849ncEffectUnlink :: ProcessId -> Identifier -> NC ()
725ncEffectUnlink :: ProcessId -> Identifier -> NC ()
@@ -857,7 +733,7 @@ ncEffectUnlink from them = do
857 postAsMessage from $ DidUnlinkNode nid
733 postAsMessage from $ DidUnlinkNode nid
858 SendPortIdentifier cid ->
734 SendPortIdentifier cid ->
859 postAsMessage from $ DidUnlinkPort cid
735 postAsMessage from $ DidUnlinkPort cid
860− modify' $ links ^: BiMultiMap.delete them from ()
736+ modify' $ linksFor them ^: Set.delete from
862-- [Unified: Table 11]
738-- [Unified: Table 11]
863ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
739ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
@@ -865,7 +741,7 @@ ncEffectUnmonitor from ref = do
865 node <- ask
741 node <- ask
866 when (isLocal node (ProcessIdentifier from)) $
742 when (isLocal node (ProcessIdentifier from)) $
867 postAsMessage from $ DidUnmonitor ref
743 postAsMessage from $ DidUnmonitor ref
868− modify' $ monitors ^: BiMultiMap.delete (monitorRefIdent ref) from ref
744+ modify' $ monitorsFor (monitorRefIdent ref) ^: Set.delete (from, ref)
870-- [Unified: Table 12]
746-- [Unified: Table 12]
871ncEffectDied :: Identifier -> DiedReason -> NC ()
747ncEffectDied :: Identifier -> DiedReason -> NC ()
@@ -880,7 +756,7 @@ ncEffectDied ident reason = do
880 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
756 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
882 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
758 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
883− forM_ uss $ \(us, _) ->
759+ forM_ uss $ \us ->
884 when (localOnly <= isLocal node (ProcessIdentifier us)) $
760 when (localOnly <= isLocal node (ProcessIdentifier us)) $
885 notifyDied us them reason Nothing
761 notifyDied us them reason Nothing
@@ -889,35 +765,9 @@ ncEffectDied ident reason = do
889 when (localOnly <= isLocal node (ProcessIdentifier us)) $
765 when (localOnly <= isLocal node (ProcessIdentifier us)) $
890 notifyDied us them reason (Just ref)
766 notifyDied us them reason (Just ref)
892− -- Notify remote nodes that the process died so it can be removed from monitor
894− mapM_ (forwardDeath node) $
895− [ nid | ProcessIdentifier pid <- [ident]
896− , i <- Set.toList $ Set.union
897− (Set.map fst $ BiMultiMap.lookupBy2nd pid unaffectedLinks)
898− (Set.map fst $ BiMultiMap.lookupBy2nd pid unaffectedMons)
899− , let nid = nodeOf i
900− , nid /= localNodeId node
903− -- Delete monitors in the local node.
904− let deleteDeads :: (Ord a, Ord v)
905− => BiMultiMap a ProcessId v -> BiMultiMap a ProcessId v
906− deleteDeads = case ident of
907− -- deleteAllBy2nd is faster than partitionWithKeyBy2nd
908− ProcessIdentifier pid -> BiMultiMap.deleteAllBy2nd pid
909− _ -> snd . BiMultiMap.partitionWithKeyBy2nd
910− (\pid _ -> ident `impliesDeathOf` ProcessIdentifier pid)
911− unaffectedLinks' = deleteDeads unaffectedLinks
912− unaffectedMons' = deleteDeads unaffectedMons
914− modify' $ (links ^= unaffectedLinks') . (monitors ^= unaffectedMons')
768+ modify' $ (links ^= unaffectedLinks) . (monitors ^= unaffectedMons)
916− -- we now consider all labels for this identifier unregistered
917− let toDrop pid = not $ ident `impliesDeathOf` ProcessIdentifier pid
770+ modify' $ registeredHere ^: Map.filter (\pid -> not $ ident `impliesDeathOf` ProcessIdentifier pid)
918− (keepNames, dropNames) <- Map.partition toDrop <$> gets (^. registeredHere)
919− mapM_ (\(p, l) -> liftIO $ trace node (MxUnRegistered l p)) (Map.toList dropNames)
920− modify' $ registeredHere ^= keepNames
922 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
772 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
923 mapM (\(pid,nidlist) ->
773 mapM (\(pid,nidlist) ->
@@ -925,15 +775,20 @@ ncEffectDied ident reason = do
926 do forM_ nidlist $ \(nid,_) ->
776 do forM_ nidlist $ \(nid,_) ->
927 when (not $ isLocal node (NodeIdentifier nid))
777 when (not $ isLocal node (NodeIdentifier nid))
928− (forwardDeath node nid)
778+ (forwardNameDeath node nid)
929 return Nothing
779 return Nothing
930 False -> return $ Just (pid,nidlist) )
780 False -> return $ Just (pid,nidlist) )
931 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
781 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
933− forwardDeath node nid = ncSendToNode nid
783+ forwardNameDeath node nid =
784+ liftIO $ sendBinary node
785+ (NodeIdentifier $ localNodeId node)
786+ (NodeIdentifier $ nid)
787+ WithImplicitReconnect
934− NCMsg { ctrlMsgSender = NodeIdentifier (localNodeId node)
789+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
935− , ctrlMsgSignal = Died ident reason
790+ , ctrlMsgSignal = Died ident reason
938-- [Unified: Table 13]
793-- [Unified: Table 13]
939ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
794ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
@@ -941,13 +796,17 @@ ncEffectSpawn pid cProc ref = do
941 mProc <- unClosure cProc
796 mProc <- unClosure cProc
942 -- If the closure does not exist, we spawn a process that throws an exception
797 -- If the closure does not exist, we spawn a process that throws an exception
943 -- This allows the remote node to find out what's happening
798 -- This allows the remote node to find out what's happening
944− -- TODO:
799+ -- TODO:
945 let proc = case mProc of
800 let proc = case mProc of
946 Left err -> fail $ "Error: Could not resolve closure: " ++ err
801 Left err -> fail $ "Error: Could not resolve closure: " ++ err
947 Right p -> p
802 Right p -> p
948 node <- ask
803 node <- ask
949 pid' <- liftIO $ forkProcess node proc
804 pid' <- liftIO $ forkProcess node proc
950− ncSendToProcess pid $ unsafeCreateUnencodedMessage $ DidSpawn ref pid'
805+ liftIO $ sendMessage node
806+ (NodeIdentifier (localNodeId node))
807+ (ProcessIdentifier pid)
808+ WithImplicitReconnect
952-- Unified semantics does not explicitly describe how to implement 'register',
811-- Unified semantics does not explicitly describe how to implement 'register',
953-- but mentions it's "very similar to nsend" (Table 14)
812-- but mentions it's "very similar to nsend" (Table 14)
@@ -965,19 +824,17 @@ ncEffectRegister from label atnode mPid reregistration = do
965 return $ (isNothing currentVal /= reregistration) &&
824 return $ (isNothing currentVal /= reregistration) &&
966 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
825 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
967 if isLocal node (NodeIdentifier atnode)
826 if isLocal node (NodeIdentifier atnode)
968− then do when isOk $
827+ then do when (isOk) $
969 do modify' $ registeredHereFor label ^= mPid
828 do modify' $ registeredHereFor label ^= mPid
970 updateRemote node currentVal mPid
829 updateRemote node currentVal mPid
971 case mPid of
830 case mPid of
972− (Just p) -> do
831+ (Just p) -> liftIO $ trace node (TraceEvRegistered p label)
974− then liftIO $ trace node (MxUnRegistered (fromJust currentVal) label)
976− liftIO $ trace node (MxRegistered p label)
977− Nothing -> liftIO $ trace node (MxUnRegistered (fromJust currentVal) label)
832+ Nothing -> liftIO $ trace node (TraceEvUnRegistered (fromJust currentVal) label)
978− newVal <- gets (^. registeredHereFor label)
833+ liftIO $ sendMessage node
979− ncSendToProcess from $ unsafeCreateUnencodedMessage $
834+ (NodeIdentifier (localNodeId node))
835+ (ProcessIdentifier from)
836+ WithImplicitReconnect
980− RegisterReply label isOk newVal
837+ (RegisterReply label isOk)
981 else let operation =
838 else let operation =
982 case reregistration of
839 case reregistration of
983 True -> flip decList
840 True -> flip decList
@@ -1007,36 +864,40 @@ ncEffectRegister from label atnode mPid reregistration = do
1007 decList (x:xs) tag = x:decList xs tag
864 decList (x:xs) tag = x:decList xs tag
1008 forward node to reg =
865 forward node to reg =
1009 when (not $ isLocal node (NodeIdentifier to)) $
866 when (not $ isLocal node (NodeIdentifier to)) $
867+ liftIO $ sendBinary node
868+ (ProcessIdentifier from)
870+ WithImplicitReconnect
1010− ncSendToNode to $ NCMsg { ctrlMsgSender = ProcessIdentifier from
872+ { ctrlMsgSender = ProcessIdentifier from
1011− , ctrlMsgSignal = reg
873+ , ctrlMsgSignal = reg
1015-- Unified semantics does not explicitly describe 'whereis'
877-- Unified semantics does not explicitly describe 'whereis'
1016ncEffectWhereIs :: ProcessId -> String -> NC ()
878ncEffectWhereIs :: ProcessId -> String -> NC ()
1017ncEffectWhereIs from label = do
879ncEffectWhereIs from label = do
1018 mPid <- gets (^. registeredHereFor label)
881 mPid <- gets (^. registeredHereFor label)
882+ liftIO $ sendMessage node
883+ (NodeIdentifier (localNodeId node))
884+ (ProcessIdentifier from)
885+ WithImplicitReconnect
1019− ncSendToProcess from $ unsafeCreateUnencodedMessage $ WhereIsReply label mPid
886+ (WhereIsReply label mPid)
1021-- [Unified: Table 14]
888-- [Unified: Table 14]
1022ncEffectNamedSend :: String -> Message -> NC ()
889ncEffectNamedSend :: String -> Message -> NC ()
1023ncEffectNamedSend label msg = do
890ncEffectNamedSend label msg = do
1024 mPid <- gets (^. registeredHereFor label)
891 mPid <- gets (^. registeredHereFor label)
1025 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
892 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
1026− forM_ mPid $ \to ->
893+ forM_ mPid $ \pid -> postMessage pid msg
1027− -- If this is a trace message we don't trace it to avoid entering a loop
1028− -- where trace messages produce more trace messages.
1029− ncSendToProcessAndTrace (label /= "trace.logger") to msg
1031-- [Issue #DP-20]
895-- [Issue #DP-20]
1032ncEffectLocalSend :: LocalNode -> ProcessId -> Message -> NC ()
896ncEffectLocalSend :: LocalNode -> ProcessId -> Message -> NC ()
1033−ncEffectLocalSend = ncEffectLocalSendAndTrace True
897+ncEffectLocalSend node to msg =
1035−ncEffectLocalSendAndTrace :: Bool -> LocalNode -> ProcessId -> Message -> NC ()
1036−ncEffectLocalSendAndTrace shouldTrace node to msg =
1037 liftIO $ withLocalProc node to $ \p -> do
898 liftIO $ withLocalProc node to $ \p -> do
1038 enqueue (processQueue p) msg
899 enqueue (processQueue p) msg
1039− when shouldTrace $ trace node (MxReceived to msg)
900+ trace node (TraceEvReceived to msg)
1041-- [Issue #DP-20]
902-- [Issue #DP-20]
1042ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
903ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
@@ -1054,12 +915,11 @@ ncEffectLocalPortSend from msg = do
1054 -- If ch is Nothing, the process has given up the read end of
915 -- If ch is Nothing, the process has given up the read end of
1055 -- the channel and we simply ignore the incoming message - this
916 -- the channel and we simply ignore the incoming message - this
1056 ch <- deRefWeak chan'
917 ch <- deRefWeak chan'
1057− forM_ ch $ \chan -> deliverChan node from msg chan
918+ forM_ ch $ \chan -> deliverChan msg chan
1058− where deliverChan :: forall a . LocalNode -> SendPortId -> Message -> TQueue a -> IO ()
919+ where deliverChan :: forall a . Message -> TQueue a -> IO ()
1059− deliverChan n p (UnencodedMessage _ raw) chan' = do
920+ deliverChan (UnencodedMessage _ raw) chan' =
1060 atomically $ writeTQueue chan' ((unsafeCoerce raw) :: a)
921 atomically $ writeTQueue chan' ((unsafeCoerce raw) :: a)
1061− trace n (MxReceivedPort p $ unsafeCreateUnencodedMessage raw)
1062− deliverChan _ _ (EncodedMessage _ _) _ =
922+ deliverChan (EncodedMessage _ _) _ =
1063 -- this will not happen unless someone screws with Primitives.hs
923 -- this will not happen unless someone screws with Primitives.hs
1064 error "invalid local channel delivery"
924 error "invalid local channel delivery"
@@ -1084,56 +944,46 @@ ncEffectGetInfo from pid =
1084 them = (ProcessIdentifier pid)
944 them = (ProcessIdentifier pid)
1086 node <- ask
946 node <- ask
1087− mProc <- liftIO $ withValidLocalState node
947+ mProc <- liftIO $
1088− $ return . (^. localProcessWithId lpid)
948+ withMVar (localState node) $ return . (^. localProcessWithId lpid)
1089 case mProc of
949 case mProc of
1090 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
950 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
1091− from (ProcessInfoNone DiedUnknownId)
951+ from node (ProcessInfoNone DiedUnknownId)
1092− Just proc -> do
952+ Just _ -> do
1093− itsLinks <- Set.map fst . BiMultiMap.lookupBy1st them <$>
953+ itsLinks <- gets (^. linksFor them)
1094− gets (^. links)
954+ itsMons <- gets (^. monitorsFor them)
1095− itsMons <- BiMultiMap.lookupBy1st them <$> gets (^. monitors)
1096 registered <- gets (^. registeredHere)
955 registered <- gets (^. registeredHere)
1097− size <- liftIO $ queueSize $ processQueue $ proc
1099 let reg = registeredNames registered
957 let reg = registeredNames registered
1100 dispatch (isLocal node (ProcessIdentifier from))
958 dispatch (isLocal node (ProcessIdentifier from))
1102 ProcessInfo {
961 ProcessInfo {
1103 infoNode = (processNodeId pid)
962 infoNode = (processNodeId pid)
1104 , infoRegisteredNames = reg
963 , infoRegisteredNames = reg
964+ -- we cannot populate this field
1105− , infoMessageQueueLength = size
965+ , infoMessageQueueLength = Nothing
1106− , infoMonitors = Set.toList itsMons
966+ , infoMonitors = Set.toList itsMons
1107− , infoLinks = Set.toList itsLinks
967+ , infoLinks = Set.toList itsLinks
1109− where dispatch :: (Serializable a)
969+ where dispatch :: (Serializable a, Show a)
1111 -> ProcessId
971 -> ProcessId
1113 -> NC ()
974 -> NC ()
1114− dispatch True dest pInfo = postAsMessage dest $ pInfo
975+ dispatch True dest _ pInfo = postAsMessage dest $ pInfo
1115− dispatch False dest pInfo =
976+ dispatch False dest node pInfo = do
1116− ncSendToProcess dest $ unsafeCreateUnencodedMessage pInfo
977+ liftIO $ sendMessage node
978+ (NodeIdentifier (localNodeId node))
979+ (ProcessIdentifier dest)
980+ WithImplicitReconnect
1118 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
983 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
1119 then (k:ks)
984 then (k:ks)
1120 else ks) []
985 else ks) []
1122−ncEffectGetNodeStats :: ProcessId -> NodeId -> NC ()
1123−ncEffectGetNodeStats from _nid = do
1125− ncState <- StateT.get
1126− nodeState <- liftIO $ withValidLocalState node return
1129− nodeStatsNode = localNodeId node
1130− , nodeStatsRegisteredNames = Map.size $ ncState ^. registeredHere
1131− , nodeStatsMonitors = BiMultiMap.size $ ncState ^. monitors
1132− , nodeStatsLinks = BiMultiMap.size $ ncState ^. links
1133− , nodeStatsProcesses = Map.size (nodeState ^. localProcesses)
1135− postAsMessage from stats
1137--------------------------------------------------------------------------------
987--------------------------------------------------------------------------------
1138-- Auxiliary --
988-- Auxiliary --
1139--------------------------------------------------------------------------------
989--------------------------------------------------------------------------------
@@ -1160,10 +1010,14 @@ notifyDied dest src reason mRef = do
1160 throwException dest $ PortLinkException pid reason
1010 throwException dest $ PortLinkException pid reason
1161 (False, _, _) ->
1011 (False, _, _) ->
1162 -- The change in sender comes from [Unified: Table 10]
1012 -- The change in sender comes from [Unified: Table 10]
1013+ liftIO $ sendBinary node
1014+ (NodeIdentifier $ localNodeId node)
1163− ncSendToNode (processNodeId dest) $ NCMsg
1015+ (NodeIdentifier $ processNodeId dest)
1016+ WithImplicitReconnect
1164− { ctrlMsgSender = NodeIdentifier (localNodeId node)
1018+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
1165− , ctrlMsgSignal = Died src reason
1019+ , ctrlMsgSignal = Died src reason
1168-- | [Unified: Table 8]
1022-- | [Unified: Table 8]
1169destNid :: ProcessSignal -> Maybe NodeId
1023destNid :: ProcessSignal -> Maybe NodeId
@@ -1175,7 +1029,6 @@ destNid (Spawn _ _) = Nothing
1175destNid (Register _ _ _ _) = Nothing
1029destNid (Register _ _ _ _) = Nothing
1176destNid (WhereIs _) = Nothing
1030destNid (WhereIs _) = Nothing
1177destNid (NamedSend _ _) = Nothing
1031destNid (NamedSend _ _) = Nothing
1178−destNid (UnreliableSend _ _) = Nothing
1179-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
1032-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
1180-- then when a local process dies the monitoring/linking machinery will take
1033-- then when a local process dies the monitoring/linking machinery will take
1181-- care of notifying remote nodes
1034-- care of notifying remote nodes
@@ -1183,7 +1036,6 @@ destNid (Died _ _) = Nothing
1183destNid (Kill pid _) = Just $ processNodeId pid
1036destNid (Kill pid _) = Just $ processNodeId pid
1184destNid (Exit pid _) = Just $ processNodeId pid
1037destNid (Exit pid _) = Just $ processNodeId pid
1185destNid (GetInfo pid) = Just $ processNodeId pid
1038destNid (GetInfo pid) = Just $ processNodeId pid
1186−destNid (GetNodeStats nid) = Just nid
1187destNid (LocalSend pid _) = Just $ processNodeId pid
1039destNid (LocalSend pid _) = Just $ processNodeId pid
1188destNid (LocalPortSend cid _) = Just $ processNodeId (sendPortProcessId cid)
1040destNid (LocalPortSend cid _) = Just $ processNodeId (sendPortProcessId cid)
1189destNid (SigShutdown) = Nothing
1041destNid (SigShutdown) = Nothing
@@ -1202,7 +1054,7 @@ unClosure closure = do
1202isValidLocalIdentifier :: Identifier -> NC Bool
1054isValidLocalIdentifier :: Identifier -> NC Bool
1203isValidLocalIdentifier ident = do
1055isValidLocalIdentifier ident = do
1204 node <- ask
1056 node <- ask
1205− liftIO . withValidLocalState node $ \nSt ->
1057+ liftIO . withMVar (localState node) $ \nSt ->
1206 case ident of
1058 case ident of
1207 NodeIdentifier nid ->
1059 NodeIdentifier nid ->
1208 return $ nid == localNodeId node
1060 return $ nid == localNodeId node
@@ -1233,9 +1085,6 @@ postMessage pid msg = do
1233throwException :: Exception e => ProcessId -> e -> NC ()
1085throwException :: Exception e => ProcessId -> e -> NC ()
1234throwException pid e = do
1086throwException pid e = do
1235 node <- ask
1087 node <- ask
1236− -- throwTo blocks until the exception is received by the target thread.
1237− -- We cannot easily make it happen asynchronpusly because then 'unlink'
1238− -- semantics would break.
1239 liftIO $ withLocalProc node pid $ \p -> throwTo (processThread p) e
1088 liftIO $ withLocalProc node pid $ \p -> throwTo (processThread p) e
1241withLocalProc :: LocalNode -> ProcessId -> (LocalProcess -> IO ()) -> IO ()
1090withLocalProc :: LocalNode -> ProcessId -> (LocalProcess -> IO ()) -> IO ()
@@ -1243,17 +1092,17 @@ withLocalProc node pid p =
1243 -- By [Unified: table 6, rule missing_process] messages to dead processes
1092 -- By [Unified: table 6, rule missing_process] messages to dead processes
1244 -- can silently be dropped
1093 -- can silently be dropped
1245 let lpid = processLocalId pid in do
1094 let lpid = processLocalId pid in do
1246− join $ withValidLocalState node $ \vst ->
1247− return $ forM_ (vst ^. localProcessWithId lpid) p
1095+ mProc <- withMVar (localState node) $ return . (^. localProcessWithId lpid)
1249--------------------------------------------------------------------------------
1098--------------------------------------------------------------------------------
1250-- Accessors --
1099-- Accessors --
1251--------------------------------------------------------------------------------
1100--------------------------------------------------------------------------------
1253−links :: Accessor NCState (BiMultiMap Identifier ProcessId ())
1102+links :: Accessor NCState (Map Identifier (Set ProcessId))
1254links = accessor _links (\ls st -> st { _links = ls })
1103links = accessor _links (\ls st -> st { _links = ls })
1256−monitors :: Accessor NCState (BiMultiMap Identifier ProcessId MonitorRef)
1105+monitors :: Accessor NCState (Map Identifier (Set (ProcessId, MonitorRef)))
1257monitors = accessor _monitors (\ms st -> st { _monitors = ms })
1106monitors = accessor _monitors (\ms st -> st { _monitors = ms })
1259registeredHere :: Accessor NCState (Map String ProcessId)
1108registeredHere :: Accessor NCState (Map String ProcessId)
@@ -1262,6 +1111,12 @@ registeredHere = accessor _registeredHere (\ry st -> st { _registeredHere = ry }
1262registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
1111registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
1263registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
1112registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
1114+linksFor :: Identifier -> Accessor NCState (Set ProcessId)
1115+linksFor ident = links >>> DAC.mapDefault Set.empty ident
1117+monitorsFor :: Identifier -> Accessor NCState (Set (ProcessId, MonitorRef))
1118+monitorsFor ident = monitors >>> DAC.mapDefault Set.empty ident
1265registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
1120registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
1266registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
1121registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
@@ -1288,12 +1143,10 @@ registeredOnNodesFor ident = registeredOnNodes >>> DAC.mapMaybe ident
1288-- * the notifications for typed channels to that process.
1143-- * the notifications for typed channels to that process.
1290-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1145-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1291−splitNotif :: (Ord a, Ord v)
1292− => Identifier
1146+splitNotif :: Identifier
1293− -> BiMultiMap Identifier a v
1147+ -> Map Identifier a
1294− -> (Map Identifier (Set (a,v)), BiMultiMap Identifier a v)
1148+ -> (Map Identifier a, Map Identifier a)
1295−splitNotif ident =
1149+splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1296− BiMultiMap.partitionWithKeyBy1st (\k !_v -> ident `impliesDeathOf` k)
1298--------------------------------------------------------------------------------
1151--------------------------------------------------------------------------------
1299-- Auxiliary --
1152-- Auxiliary --