@@ -1,3 +1,12 @@
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE ScopedTypeVariables #-}
4+{-# LANGUAGE RankNTypes #-}
5+{-# LANGUAGE BangPatterns #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE RecordWildCards #-}
8+{-# LANGUAGE MagicHash #-}
1-- | Local nodes
10-- | Local nodes
3module Control.Distributed.Process.Node
12module Control.Distributed.Process.Node
@@ -12,10 +21,6 @@ module Control.Distributed.Process.Node
13-- TODO: Calls to 'sendBinary' and co (by the NC) may stall the node controller.
22-- 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)
19import System.IO (fixIO, hPutStrLn, stderr)
24import System.IO (fixIO, hPutStrLn, stderr)
20import System.Mem.Weak (Weak, deRefWeak)
25import System.Mem.Weak (Weak, deRefWeak)
21import qualified Data.ByteString.Lazy as BSL (fromChunks)
26import qualified Data.ByteString.Lazy as BSL (fromChunks)
@@ -23,45 +28,73 @@ import Data.Binary (decode)
23import Data.Map (Map)
28import Data.Map (Map)
24import qualified Data.Map as Map
29import qualified Data.Map as Map
27 , fromList
33 , fromList
29 , partitionWithKey
37 , partitionWithKey
31 , filterWithKey
40 , filterWithKey
32 , foldlWithKey
41 , 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)
34import Data.Set (Set)
49import Data.Set (Set)
35import qualified Data.Set as Set
50import qualified Data.Set as Set
42import Data.Foldable (forM_)
59import Data.Foldable (forM_)
43−import Data.Maybe (isJust, isNothing, catMaybes)
60+import Data.Maybe (isJust, fromJust, isNothing, catMaybes)
44import Data.Typeable (Typeable)
61import Data.Typeable (Typeable)
45import Control.Category ((>>>))
62import Control.Category ((>>>))
46−import Control.Applicative ((<$>))
63+import Control.Applicative
47−import Control.Monad (void, when)
64+import Control.Monad (void, when, join)
48import Control.Monad.IO.Class (MonadIO, liftIO)
65import Control.Monad.IO.Class (MonadIO, liftIO)
49import Control.Monad.State.Strict (MonadState, StateT, evalStateT, gets)
66import Control.Monad.State.Strict (MonadState, StateT, evalStateT, gets)
50import qualified Control.Monad.State.Strict as StateT (get, put)
67import qualified Control.Monad.State.Strict as StateT (get, put)
51import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask)
68import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask)
52−import Control.Exception (throwIO, SomeException, Exception, throwTo)
69+import Control.Exception
74+ , uninterruptibleMask_
53−import qualified Control.Exception as Exception (catch)
78+import qualified Control.Exception as Exception
54−import Control.Concurrent (forkIO)
84+import Control.Concurrent (forkIO, killThread)
85+import Control.Distributed.Process.Internal.BiMultiMap (BiMultiMap)
86+import qualified Control.Distributed.Process.Internal.BiMultiMap as BiMultiMap
55import Control.Distributed.Process.Internal.StrictMVar
87import Control.Distributed.Process.Internal.StrictMVar
57 , withMVar
89 , withMVar
58 , modifyMVar
91 , modifyMVar
60 , newEmptyMVar
92 , newEmptyMVar
62 , takeMVar
94 , takeMVar
64import Control.Concurrent.Chan (newChan, writeChan, readChan)
96import Control.Concurrent.Chan (newChan, writeChan, readChan)
97+import qualified Control.Concurrent.MVar as MVar (newEmptyMVar, takeMVar)
65import Control.Concurrent.STM
98import Control.Concurrent.STM
66 ( atomically
99 ( atomically
@@ -70,6 +103,7 @@ import Control.Distributed.Process.Internal.CQueue
70 , enqueue
103 , enqueue
71 , newCQueue
104 , newCQueue
72 , mkWeakCQueue
105 , mkWeakCQueue
74import qualified Network.Transport as NT
108import qualified Network.Transport as NT
75 ( Transport
109 ( Transport
@@ -81,8 +115,8 @@ import qualified Network.Transport as NT
81 , TransportError(..)
115 , TransportError(..)
82 , address
116 , address
83 , closeEndPoint
117 , closeEndPoint
85 , Connection
118 , Connection
87 , EndPointAddress
121 , EndPointAddress
88 , Reliability(ReliableOrdered)
122 , Reliability(ReliableOrdered)
@@ -99,8 +133,11 @@ import Control.Distributed.Process.Internal.Types
99 , LocalProcessId(..)
133 , LocalProcessId(..)
100 , ProcessId(..)
134 , ProcessId(..)
101 , LocalNode(..)
135 , LocalNode(..)
102− , Tracer(InactiveTracer)
136+ , MxEventBus(..)
103 , LocalNodeState(..)
137 , LocalNodeState(..)
138+ , ValidLocalNodeState(..)
139+ , withValidLocalState
140+ , modifyValidLocalState
104 , LocalProcess(..)
141 , LocalProcess(..)
105 , LocalProcessState(..)
142 , LocalProcessState(..)
106 , Process(..)
143 , Process(..)
@@ -110,9 +147,11 @@ import Control.Distributed.Process.Internal.Types
110 , localPidCounter
147 , localPidCounter
111 , localPidUnique
148 , localPidUnique
112 , localProcessWithId
149 , localProcessWithId
113 , localConnections
151 , localConnections
114 , forever'
152 , forever'
115 , MonitorRef(..)
153 , MonitorRef(..)
154+ , NodeClosedException(..)
116 , ProcessMonitorNotification(..)
155 , ProcessMonitorNotification(..)
117 , NodeMonitorNotification(..)
156 , NodeMonitorNotification(..)
118 , PortMonitorNotification(..)
157 , PortMonitorNotification(..)
@@ -126,58 +165,87 @@ import Control.Distributed.Process.Internal.Types
126 , DidUnlinkPort(..)
165 , DidUnlinkPort(..)
127 , SpawnRef
166 , SpawnRef
128 , DidSpawn(..)
167 , DidSpawn(..)
129− , Message
168+ , Message(..)
130 , TypedChannel(..)
169 , TypedChannel(..)
131 , Identifier(..)
170 , Identifier(..)
133 , ProcessInfo(..)
172 , ProcessInfo(..)
134 , ProcessInfoNone(..)
173 , ProcessInfoNone(..)
135 , SendPortId(..)
175 , SendPortId(..)
136 , typedChannelWithId
176 , typedChannelWithId
137 , RegisterReply(..)
177 , RegisterReply(..)
138 , WhereIsReply(..)
178 , WhereIsReply(..)
140 , payloadToMessage
179 , payloadToMessage
141− , createMessage
180+ , createUnencodedMessage
181+ , unsafeCreateUnencodedMessage
142 , runLocalProcess
182 , runLocalProcess
143 , firstNonReservedProcessId
183 , firstNonReservedProcessId
144− , ImplicitReconnect(WithImplicitReconnect, NoImplicitReconnect)
184+ , 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
146−import Control.Distributed.Process.Internal.Trace
195+import Control.Distributed.Process.Management.Internal.Trace.Tracer
198+import Control.Distributed.Process.Management.Internal.Trace.Types
147 ( TraceArg(..)
199 ( TraceArg(..)
148− , traceFormat
200+ , traceEvent
149− , startTracing
201+ , traceLogFmt
150− , stopTracer
202+ , enableTrace
152import Control.Distributed.Process.Serializable (Serializable)
204import Control.Distributed.Process.Serializable (Serializable)
153import Control.Distributed.Process.Internal.Messaging
205import Control.Distributed.Process.Internal.Messaging
154 ( sendBinary
206 ( sendBinary
157 , closeImplicitReconnections
207 , closeImplicitReconnections
158 , impliesDeathOf
208 , impliesDeathOf
160import Control.Distributed.Process.Internal.Primitives
210import Control.Distributed.Process.Internal.Primitives
161 ( register
211 ( register
163 , receiveWait
212 , receiveWait
165 , sendChan
214 , sendChan
167−import Control.Distributed.Process.Internal.Types (SendPort)
221+import Control.Distributed.Process.Internal.Types (SendPort, Tracer(..))
168import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
222import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
169−import Control.Distributed.Process.Internal.WeakTQueue (writeTQueue)
223+import Control.Distributed.Process.Internal.WeakTQueue (TQueue, writeTQueue)
170import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
224import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
171 ( mapMaybe
225 ( mapMaybe
172 , mapDefault
226 , mapDefault
228+import Control.Monad.Catch (try)
229+import GHC.IO (IO(..), unsafeUnmask)
230+import GHC.Base ( maskAsyncExceptions# )
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
175--------------------------------------------------------------------------------
243--------------------------------------------------------------------------------
176-- Initialization --
244-- Initialization --
177--------------------------------------------------------------------------------
245--------------------------------------------------------------------------------
179initRemoteTable :: RemoteTable
247initRemoteTable :: RemoteTable
180−initRemoteTable = BuiltIn.remoteTable Static.initRemoteTable
248+initRemoteTable = Trace.remoteTable $ BuiltIn.remoteTable Static.initRemoteTable
182-- | Initialize a new local node.
250-- | Initialize a new local node.
183newLocalNode :: NT.Transport -> RemoteTable -> IO LocalNode
251newLocalNode :: NT.Transport -> RemoteTable -> IO LocalNode
@@ -193,68 +261,133 @@ newLocalNode transport rtable = do
193-- | Create a new local node (without any service processes running)
261-- | Create a new local node (without any service processes running)
194createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
262createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
195createBareLocalNode endPoint rtable = do
263createBareLocalNode endPoint rtable = do
196− unq <- randomIO
264+ unq <- randomIO
197− state <- newMVar LocalNodeState
265+ state <- newMVar $ LocalNodeValid $ ValidLocalNodeState
198− { _localProcesses = Map.empty
266+ { _localProcesses = Map.empty
199− , _localPidCounter = firstNonReservedProcessId
267+ , _localPidCounter = firstNonReservedProcessId
200− , _localPidUnique = unq
268+ , _localPidUnique = unq
201− , _localConnections = Map.empty
269+ , _localConnections = Map.empty
203− ctrlChan <- newChan
271+ ctrlChan <- newChan
204− let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
272+ let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
205− , localEndPoint = endPoint
273+ , localEndPoint = endPoint
206− , localState = state
274+ , localState = state
207− , localCtrlChan = ctrlChan
275+ , localCtrlChan = ctrlChan
208− , localTracer = InactiveTracer
276+ , localEventBus = MxEventBusInitialising
209− , remoteTable = rtable
277+ , remoteTable = rtable
211− tracedNode <- startTracing node
279+ tracedNode <- startMxAgent node
281+ -- Once the NC terminates, the endpoint isn't much use,
212− void . forkIO $ runNodeController tracedNode
282+ void $ forkIO $ Exception.finally (runNodeController tracedNode)
283+ (NT.closeEndPoint (localEndPoint node))
285+ -- whilst a closed/failing endpoint will terminate the NC
213− void . forkIO $ handleIncomingMessages tracedNode
286+ void $ forkIO $ Exception.finally (handleIncomingMessages tracedNode)
292+ writeChan (localCtrlChan node) NCMsg
293+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
294+ , ctrlMsgSignal = SigShutdown
297+startMxAgent :: LocalNode -> IO LocalNode
298+startMxAgent node = do
299+ -- see note [tracer/forkProcess races]
300+ let fork = forkProcess node
301+ mv <- MVar.newEmptyMVar
302+ pid <- fork $ mxAgentController fork mv
303+ (tracer', wqRef, mxNew') <- MVar.takeMVar mv
304+ return node { localEventBus = (MxEventBus pid tracer' wqRef mxNew') }
306+startDefaultTracer :: LocalNode -> IO ()
307+startDefaultTracer node' = do
308+ let t = localEventBus node'
310+ MxEventBus _ (Tracer pid _) _ _ -> do
311+ runProcess node' $ register "trace.controller" pid
312+ pid' <- forkProcess node' defaultTracer
313+ enableTrace (localEventBus node') pid'
314+ runProcess node' $ register "tracer.initial" pid'
214− return tracedNode
315+ _ -> return ()
317+-- TODO: we need a better mechanism for defining and registering services
216-- | Start and register the service processes on a node
319-- | Start and register the service processes on a node
217−-- (for now, this is only the logger)
218startServiceProcesses :: LocalNode -> IO ()
320startServiceProcesses :: LocalNode -> IO ()
219startServiceProcesses node = do
321startServiceProcesses node = do
322+ -- tracing /spawns/ relies on the tracer being enabled, but we start
323+ -- the default tracer first, even though it might @nsend@ to the logger
324+ -- before /that/ process has started - this is a totally harmless race
325+ -- however, so we deliberably ignore it
326+ startDefaultTracer node
220 logger <- forkProcess node loop
327 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.
221− runProcess node $ register "logger" logger
333+ register "trace.logger" logger
223− loop = do
335+ loop = do
224− receiveWait
336+ receiveWait
225− [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
337+ [ match $ \(SayMessage time pid string) -> do
338+ let time' = formatTime defaultTimeLocale "%c" time
226− liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
339+ liftIO . hPutStrLn stderr $ time' ++ " " ++ show pid ++ ": " ++ string
228− , match $ \((time, string) :: (String, String)) -> do
341+ , match $ \((time, string) :: (String, String)) -> do
229− -- this is a 'trace' message from the local node tracer
342+ -- this is a 'trace' message from the local node tracer
230− liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
343+ liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
232− , match $ \(ch :: SendPort ()) -> -- a shutdown request
345+ , match $ \(ch :: SendPort ()) -> -- a shutdown request
233− sendChan ch ()
346+ sendChan ch ()
236−-- | Force-close a local node
349+-- | Force-close a local node, killing all processes on that node.
238−-- TODO: for now we just close the associated endpoint
239closeLocalNode :: LocalNode -> IO ()
350closeLocalNode :: LocalNode -> IO ()
240−closeLocalNode node =
351+closeLocalNode node = do
352+ -- Kill processes after refilling the mvar. Otherwise, there is potential for
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').
241 NT.closeEndPoint (localEndPoint node)
368 NT.closeEndPoint (localEndPoint node)
243-- | Run a process on a local node and wait for it to finish
370-- | Run a process on a local node and wait for it to finish
244runProcess :: LocalNode -> Process () -> IO ()
371runProcess :: LocalNode -> Process () -> IO ()
245runProcess node proc = do
372runProcess node proc = do
246 done <- newEmptyMVar
373 done <- newEmptyMVar
374+ -- TODO; When forkProcess inherits the masking state, protect the forked
375+ -- thread against async exceptions that could occur before 'try' is evaluated.
247− void $ forkProcess node (proc `finally` liftIO (putMVar done ()))
376+ void $ forkProcess node $ try proc >>= liftIO . putMVar done
248− takeMVar done
377+ takeMVar done >>= either (throwIO :: SomeException -> IO a) return
250-- | Spawn a new process on a local node
379-- | Spawn a new process on a local node
251forkProcess :: LocalNode -> Process () -> IO ProcessId
380forkProcess :: LocalNode -> Process () -> IO ProcessId
381+forkProcess node proc = do
382+ ms <- getMaskingState
252−forkProcess node proc = modifyMVar (localState node) startProcess
383+ modifyMVarMasked (localState node) (startProcess ms)
385+ startProcess :: MaskingState
254− startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
387+ -> IO (LocalNodeState, ProcessId)
255− startProcess st = do
388+ startProcess ms (LocalNodeValid vst) = do
256− let lpid = LocalProcessId { lpidCounter = st ^. localPidCounter
389+ let lpid = LocalProcessId { lpidCounter = vst ^. localPidCounter
257− , lpidUnique = st ^. localPidUnique
390+ , lpidUnique = vst ^. localPidUnique
259 let pid = ProcessId { processNodeId = localNodeId node
392 let pid = ProcessId { processNodeId = localNodeId node
260 , processLocalId = lpid
393 , processLocalId = lpid
@@ -274,43 +407,81 @@ forkProcess node proc = modifyMVar (localState node) startProcess
274 , processThread = tid
407 , processThread = tid
275 , processNode = node
408 , 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
277− tid' <- forkIO $ do
416+ tid' <- uninterruptibleMask_ $ forkIO $ do
278− reason <- Exception.catch
417+ reason <- Exception.catches
279− (runLocalProcess lproc proc >> return DiedNormal)
418+ (unmask $ runLocalProcess lproc proc >> return DiedNormal)
419+ [ (Exception.Handler (\ex@(ProcessExitException from msg) -> do
420+ mMsg <- unwrapMessage msg :: IO (Maybe String)
422+ Nothing -> return $ DiedException $ show ex
423+ Just m -> return $ DiedException ("exit-from=" ++ (show from) ++ ",reason=" ++ m)))
424+ , (Exception.Handler
280− (return . DiedException . (show :: SomeException -> String))
425+ (return . DiedException . (show :: SomeException -> String)))]
282 -- [Unified: Table 4, rules termination and exiting]
427 -- [Unified: Table 4, rules termination and exiting]
283− modifyMVar_ (localState node) (cleanupProcess pid)
428+ mconns <- modifyValidLocalState 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
284 writeChan (localCtrlChan node) NCMsg
434 writeChan (localCtrlChan node) NCMsg
285 { ctrlMsgSender = ProcessIdentifier pid
435 { ctrlMsgSender = ProcessIdentifier pid
286 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
436 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
288 return (tid', lproc)
438 return (tid', lproc)
440+ -- see note [tracer/forkProcess races]
441+ trace node (MxSpawned pid)
290 if lpidCounter lpid == maxBound
443 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!?
292 newUnique <- randomIO
447 newUnique <- randomIO
448+ return ( LocalNodeValid
293− return ( (localProcessWithId lpid ^= Just lproc)
449+ $ (localProcessWithId lpid ^= Just lproc)
294 . (localPidCounter ^= firstNonReservedProcessId)
450 . (localPidCounter ^= firstNonReservedProcessId)
295 . (localPidUnique ^= newUnique)
451 . (localPidUnique ^= newUnique)
456+ return ( LocalNodeValid
300− return ( (localProcessWithId lpid ^= Just lproc)
457+ $ (localProcessWithId lpid ^= Just lproc)
301 . (localPidCounter ^: (+ 1))
458 . (localPidCounter ^: (+ 1))
462+ startProcess _ LocalNodeClosed =
463+ throwIO $ NodeClosedException $ localNodeId node
306− cleanupProcess :: ProcessId -> LocalNodeState -> IO LocalNodeState
465+ cleanupProcess :: ProcessId
466+ -> ValidLocalNodeState
467+ -> IO (ValidLocalNodeState, [NT.Connection])
307− cleanupProcess pid st = do
468+ cleanupProcess pid vst = do
308 let pid' = ProcessIdentifier pid
469 let pid' = ProcessIdentifier pid
309− let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (st ^. localConnections)
470+ let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (vst ^. localConnections)
310− mapM_ (NT.close . fst) (Map.elems affected)
311− return $ (localProcessWithId (processLocalId pid) ^= Nothing)
471+ return ( (localProcessWithId (processLocalId pid) ^= Nothing)
312− . (localConnections ^= unaffected)
472+ . (localConnections ^= unaffected)
474+ , map fst $ Map.elems affected
477+-- note [tracer/forkProcess races]
479+-- Our startTracing function uses forkProcess to start the trace controller
480+-- process, and of course forkProcess attempts to call traceEvent once the
481+-- process has started. This is harmless, as the localEventBus is not updated
482+-- until /after/ the initial forkProcess completes, so the first call to
483+-- traceEvent behaves as if tracing were disabled (i.e., it is ignored).
315--------------------------------------------------------------------------------
486--------------------------------------------------------------------------------
316-- Handle incoming messages --
487-- Handle incoming messages --
@@ -320,8 +491,8 @@ type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
321data IncomingTarget =
492data IncomingTarget =
323− | ToProc (Weak (CQueue Message))
494+ | ToProc ProcessId (Weak (CQueue Message))
324− | ToChan TypedChannel
495+ | ToChan SendPortId TypedChannel
327data ConnectionState = ConnectionState {
498data ConnectionState = ConnectionState {
@@ -348,6 +519,7 @@ incomingFrom addr = aux >>> DAC.mapDefault Set.empty addr
349handleIncomingMessages :: LocalNode -> IO ()
520handleIncomingMessages :: LocalNode -> IO ()
350handleIncomingMessages node = go initConnectionState
521handleIncomingMessages node = go initConnectionState
522+ `Exception.catch` \(NodeClosedException _) -> return ()
352 go :: ConnectionState -> IO ()
524 go :: ConnectionState -> IO ()
353 go !st = do
525 go !st = do
@@ -355,28 +527,37 @@ handleIncomingMessages node = go initConnectionState
355 case event of
527 case event of
356 NT.ConnectionOpened cid rel theirAddr ->
528 NT.ConnectionOpened cid rel theirAddr ->
357 if rel == NT.ReliableOrdered
529 if rel == NT.ReliableOrdered
531+ trace node (MxConnected cid theirAddr)
358− then go ( (incomingAt cid ^= Just (theirAddr, Uninit))
533+ (incomingAt cid ^= Just (theirAddr, Uninit))
359 . (incomingFrom theirAddr ^: Set.insert cid)
534 . (incomingFrom theirAddr ^: Set.insert cid)
362− else invalidRequest cid st
537+ else invalidRequest cid st $
538+ "attempt to connect with unsupported reliability " ++ show rel
363 NT.Received cid payload ->
539 NT.Received cid payload ->
364 case st ^. incomingAt cid of
540 case st ^. incomingAt cid of
365− Just (_, ToProc weakQueue) -> do
541+ Just (_, ToProc pid weakQueue) -> do
366 mQueue <- deRefWeak weakQueue
542 mQueue <- deRefWeak weakQueue
367 forM_ mQueue $ \queue -> do
543 forM_ mQueue $ \queue -> do
368 -- TODO: if we find that the queue is Nothing, should we remove
544 -- TODO: if we find that the queue is Nothing, should we remove
369 -- it from the NC state? (and same for channels, below)
545 -- it from the NC state? (and same for channels, below)
370 let msg = payloadToMessage payload
546 let msg = payloadToMessage payload
371 enqueue queue msg -- 'enqueue' is strict
547 enqueue queue msg -- 'enqueue' is strict
548+ trace node (MxReceived pid msg)
373− Just (_, ToChan (TypedChannel chan')) -> do
550+ Just (_, ToChan chId (TypedChannel chan')) -> do
374 mChan <- deRefWeak chan'
551 mChan <- deRefWeak chan'
375 -- If mChan is Nothing, the process has given up the read end of
552 -- If mChan is Nothing, the process has given up the read end of
376 -- the channel and we simply ignore the incoming message
553 -- the channel and we simply ignore the incoming message
377− forM_ mChan $ \chan -> atomically $
554+ forM_ mChan $ \chan -> do
555+ msg' <- atomically $ do
556+ msg <- return $! decode (BSL.fromChunks payload)
378− -- We make sure the message is fully decoded when it is enqueued
557+ -- We make sure the message is fully decoded when it is enqueued
379− writeTQueue chan $! decode (BSL.fromChunks payload)
558+ writeTQueue chan msg
560+ trace node $ MxReceivedPort chId $ unsafeCreateUnencodedMessage msg'
381 Just (_, ToNode) -> do
562 Just (_, ToNode) -> do
382 let ctrlMsg = decode . BSL.fromChunks $ payload
563 let ctrlMsg = decode . BSL.fromChunks $ payload
@@ -386,37 +567,49 @@ handleIncomingMessages node = go initConnectionState
386 case decode (BSL.fromChunks payload) of
567 case decode (BSL.fromChunks payload) of
387 ProcessIdentifier pid -> do
568 ProcessIdentifier pid -> do
388 let lpid = processLocalId pid
569 let lpid = processLocalId pid
389− mProc <- withMVar state $ return . (^. localProcessWithId lpid)
570+ mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
390 case mProc of
571 case mProc of
391 Just proc ->
572 Just proc ->
392− go (incomingAt cid ^= Just (src, ToProc (processWeakQ proc)) $ st)
573+ go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
393 Nothing ->
574 Nothing ->
394− invalidRequest cid st
575+ -- incoming attempt to connect to unknown process - might
577+ go (incomingAt cid ^= Nothing $ st)
395 SendPortIdentifier chId -> do
578 SendPortIdentifier chId -> do
396 let lcid = sendPortLocalId chId
579 let lcid = sendPortLocalId chId
397 lpid = processLocalId (sendPortProcessId chId)
580 lpid = processLocalId (sendPortProcessId chId)
398− mProc <- withMVar state $ return . (^. localProcessWithId lpid)
581+ mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
399 case mProc of
582 case mProc of
400 Just proc -> do
583 Just proc -> do
401 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
584 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
402 case mChannel of
585 case mChannel of
403 Just channel ->
586 Just channel ->
404− go (incomingAt cid ^= Just (src, ToChan channel) $ st)
587+ go (incomingAt cid ^= Just (src, ToChan chId channel) $ st)
405 Nothing ->
588 Nothing ->
406− invalidRequest cid st
589+ invalidRequest cid st $
590+ "incoming attempt to connect to unknown channel of"
591+ ++ " process " ++ show (sendPortProcessId chId)
407 Nothing ->
592 Nothing ->
408− invalidRequest cid st
593+ -- incoming attempt to connect to channel of unknown
594+ -- process - might be dead already
595+ go (incomingAt cid ^= Nothing $ st)
409 NodeIdentifier nid ->
596 NodeIdentifier nid ->
410 if nid == localNodeId node
597 if nid == localNodeId node
411 then go (incomingAt cid ^= Just (src, ToNode) $ st)
598 then go (incomingAt cid ^= Just (src, ToNode) $ st)
412− else invalidRequest cid st
599+ 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 "
413 Nothing ->
604 Nothing ->
414 invalidRequest cid st
605 invalidRequest cid st
606+ "message received from an unknown connection"
415 NT.ConnectionClosed cid ->
607 NT.ConnectionClosed cid ->
416 case st ^. incomingAt cid of
608 case st ^. incomingAt cid of
417 Nothing ->
609 Nothing ->
418− invalidRequest cid st
610+ invalidRequest cid st "closed unknown connection"
419− Just (src, _) ->
611+ Just (src, _) -> do
612+ trace node (MxDisconnected cid src)
420 go ( (incomingAt cid ^= Nothing)
613 go ( (incomingAt cid ^= Nothing)
421 . (incomingFrom src ^: Set.delete cid)
614 . (incomingFrom src ^: Set.delete cid)
@@ -435,32 +628,30 @@ handleIncomingMessages node = go initConnectionState
437 NT.ErrorEvent (NT.TransportError NT.EventEndPointFailed str) ->
630 NT.ErrorEvent (NT.TransportError NT.EventEndPointFailed str) ->
438− fatal $ "Cloud Haskell fatal error: end point failed: " ++ str
631+ fail $ "Cloud Haskell fatal error: end point failed: " ++ str
439 NT.ErrorEvent (NT.TransportError NT.EventTransportFailed str) ->
632 NT.ErrorEvent (NT.TransportError NT.EventTransportFailed str) ->
440− fatal $ "Cloud Haskell fatal error: transport failed: " ++ str
633+ fail $ "Cloud Haskell fatal error: transport failed: " ++ str
441 NT.EndPointClosed ->
634 NT.EndPointClosed ->
442− stopTracer (localTracer node) >> return ()
635+ return ()
443 NT.ReceivedMulticast _ _ ->
636 NT.ReceivedMulticast _ _ ->
444 -- If we received a multicast message, something went horribly wrong
637 -- If we received a multicast message, something went horribly wrong
445 -- and we just give up
638 -- and we just give up
446− fatal "Cloud Haskell fatal error: received unexpected multicast"
639+ fail "Cloud Haskell fatal error: received unexpected multicast"
448− fatal :: String -> IO ()
449− fatal msg = stopTracer (localTracer node) >> fail msg
451− invalidRequest :: NT.ConnectionId -> ConnectionState -> IO ()
641+ invalidRequest :: NT.ConnectionId -> ConnectionState -> String -> IO ()
452− invalidRequest cid st = do
642+ invalidRequest cid st msg = do
453 -- TODO: We should treat this as a fatal error on the part of the remote
643 -- TODO: We should treat this as a fatal error on the part of the remote
454 -- node. That is, we should report the remote node as having died, and we
644 -- node. That is, we should report the remote node as having died, and we
455 -- should close incoming connections (this requires a Transport layer
645 -- should close incoming connections (this requires a Transport layer
456 -- extension).
646 -- extension).
457− traceEventFmtIO node "" [(TraceStr "[network] invalid request: "),
647+ traceEventFmtIO node "" [ TraceStr $ " [network] invalid request"
648+ ++ " (" ++ msg ++ "): "
458− (Trace cid)]
649+ , (Trace cid)
459 go ( incomingAt cid ^= Nothing
651 go ( incomingAt cid ^= Nothing
463− state = localState node
464 endpoint = localEndPoint node
655 endpoint = localEndPoint node
465 ctrlChan = localCtrlChan node
656 ctrlChan = localCtrlChan node
@@ -469,8 +660,9 @@ handleIncomingMessages node = go initConnectionState
469--------------------------------------------------------------------------------
660--------------------------------------------------------------------------------
471runNodeController :: LocalNode -> IO ()
662runNodeController :: LocalNode -> IO ()
472−runNodeController =
663+runNodeController node =
473− runReaderT (evalStateT (unNC nodeController) initNCState)
664+ runReaderT (evalStateT (unNC nodeController) initNCState) node
665+ `Exception.catch` \(NodeClosedException _) -> return ()
475--------------------------------------------------------------------------------
667--------------------------------------------------------------------------------
476-- Internal data types --
668-- Internal data types --
@@ -478,20 +670,26 @@ runNodeController =
479data NCState = NCState
671data NCState = NCState
480 { -- Mapping from remote processes to linked local processes
672 { -- Mapping from remote processes to linked local processes
481− _links :: !(Map Identifier (Set ProcessId))
673+ _links :: !(BiMultiMap Identifier ProcessId ())
482 -- Mapping from remote processes to monitoring local processes
674 -- Mapping from remote processes to monitoring local processes
483− , _monitors :: !(Map Identifier (Set (ProcessId, MonitorRef)))
675+ , _monitors :: !(BiMultiMap Identifier ProcessId MonitorRef)
484 -- Process registry: names and where they live, mapped to the PIDs
676 -- Process registry: names and where they live, mapped to the PIDs
485 , _registeredHere :: !(Map String ProcessId)
677 , _registeredHere :: !(Map String ProcessId)
486 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
678 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
489newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
681newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
682+ deriving ( Applicative
686+ , MonadState NCState
490− deriving (Functor, Monad, MonadIO, MonadState NCState, MonadReader LocalNode)
687+ , MonadReader LocalNode
492initNCState :: NCState
690initNCState :: NCState
493−initNCState = NCState { _links = Map.empty
691+initNCState = NCState { _links = BiMultiMap.empty
494− , _monitors = Map.empty
692+ , _monitors = BiMultiMap.empty
495 , _registeredHere = Map.empty
693 , _registeredHere = Map.empty
496 , _registeredOnNodes = Map.empty
694 , _registeredOnNodes = Map.empty
@@ -507,34 +705,60 @@ instance Show ProcessKillException where
507 show (ProcessKillException pid reason) =
705 show (ProcessKillException pid reason) =
508 "killed-by=" ++ show pid ++ ",reason=" ++ reason
706 "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
510--------------------------------------------------------------------------------
735--------------------------------------------------------------------------------
511-- Tracing/Debugging --
736-- Tracing/Debugging --
512--------------------------------------------------------------------------------
737--------------------------------------------------------------------------------
514−-- [Issue #104]
739+-- [Issue #104 / DP-13]
516traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
741traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
517traceNotifyDied node ident reason =
742traceNotifyDied node ident reason =
743+ -- TODO: sendPortDied notifications
744+ liftIO $ withLocalTracer node $ \t ->
518− case reason of
745+ case ident of
746+ (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
747+ (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
519− DiedNormal -> return ()
748+ _ -> return ()
520− _ -> traceNcEventFmt node " "
521− [(TraceStr "[node-controller]"),
525−traceNcEventFmt :: LocalNode -> String -> [TraceArg] -> NC ()
526−traceNcEventFmt node fmt args =
527− liftIO $ traceEventFmtIO node fmt args
529traceEventFmtIO :: LocalNode
750traceEventFmtIO :: LocalNode
530 -> String
751 -> String
531 -> [TraceArg]
752 -> [TraceArg]
533traceEventFmtIO node fmt args =
754traceEventFmtIO node fmt args =
534− withLocalTracer node $ \t -> traceFormat t fmt args
755+ withLocalTracer node $ \t -> traceLogFmt t fmt args
536−withLocalTracer :: LocalNode -> (Tracer -> IO ()) -> IO ()
757+trace :: LocalNode -> MxEvent -> IO ()
758+trace node ev = withLocalTracer node $ \t -> traceEvent t ev
760+withLocalTracer :: LocalNode -> (MxEventBus -> IO ()) -> IO ()
537−withLocalTracer node act = act (localTracer node)
761+withLocalTracer node act = act (localEventBus node)
539--------------------------------------------------------------------------------
763--------------------------------------------------------------------------------
540-- Core functionality --
764-- Core functionality --
@@ -550,11 +774,7 @@ nodeController = do
550 -- [Unified: Table 7, rule nc_forward]
774 -- [Unified: Table 7, rule nc_forward]
551 case destNid (ctrlMsgSignal msg) of
775 case destNid (ctrlMsgSignal msg) of
552 Just nid' | nid' /= localNodeId node ->
776 Just nid' | nid' /= localNodeId node ->
553− liftIO $ sendBinary node
777+ ncSendToNode nid' msg
555− (NodeIdentifier nid')
556− WithImplicitReconnect
559 return ()
779 return ()
@@ -575,14 +795,26 @@ nodeController = do
575 ncEffectRegister from label atnode pid force
795 ncEffectRegister from label atnode pid force
576 NCMsg (ProcessIdentifier from) (WhereIs label) ->
796 NCMsg (ProcessIdentifier from) (WhereIs label) ->
577 ncEffectWhereIs from label
797 ncEffectWhereIs from label
578− NCMsg from (NamedSend label msg') ->
798+ NCMsg _ (NamedSend label msg') ->
579− ncEffectNamedSend from label msg'
799+ ncEffectNamedSend label msg'
800+ NCMsg _ (UnreliableSend lpid msg') ->
801+ ncEffectLocalSend node (ProcessId (localNodeId node) lpid) msg'
802+ NCMsg _ (LocalSend to msg') ->
803+ ncEffectLocalSend node to msg'
804+ NCMsg _ (LocalPortSend to msg') ->
805+ ncEffectLocalPortSend to msg'
580 NCMsg (ProcessIdentifier from) (Kill to reason) ->
806 NCMsg (ProcessIdentifier from) (Kill to reason) ->
581 ncEffectKill from to reason
807 ncEffectKill from to reason
582 NCMsg (ProcessIdentifier from) (Exit to reason) ->
808 NCMsg (ProcessIdentifier from) (Exit to reason) ->
583 ncEffectExit from to reason
809 ncEffectExit from to reason
584 NCMsg (ProcessIdentifier from) (GetInfo pid) ->
810 NCMsg (ProcessIdentifier from) (GetInfo pid) ->
585 ncEffectGetInfo from pid
811 ncEffectGetInfo from pid
812+ NCMsg _ SigShutdown ->
814+ NT.closeEndPoint (localEndPoint node)
815+ `Exception.finally` throwIO (NodeClosedException $ localNodeId node)
816+ NCMsg (ProcessIdentifier from) (GetNodeStats nid) ->
817+ ncEffectGetNodeStats from nid
586 unexpected ->
818 unexpected ->
587 error $ "nodeController: unexpected message " ++ show unexpected
819 error $ "nodeController: unexpected message " ++ show unexpected
@@ -600,22 +832,18 @@ ncEffectMonitor from them mRef = do
600 case (shouldLink, isLocal node (ProcessIdentifier from)) of
832 case (shouldLink, isLocal node (ProcessIdentifier from)) of
601 (True, _) -> -- [Unified: first rule]
833 (True, _) -> -- [Unified: first rule]
602 case mRef of
834 case mRef of
603− Just ref -> modify' $ monitorsFor them ^: Set.insert (from, ref)
835+ Just ref -> modify' $ monitors ^: BiMultiMap.insert them from ref
604− Nothing -> modify' $ linksFor them ^: Set.insert from
836+ Nothing -> modify' $ links ^: BiMultiMap.insert them from ()
605 (False, True) -> -- [Unified: second rule]
837 (False, True) -> -- [Unified: second rule]
606 notifyDied from them DiedUnknownId mRef
838 notifyDied from them DiedUnknownId mRef
607 (False, False) -> -- [Unified: third rule]
839 (False, False) -> -- [Unified: third rule]
608 -- TODO: this is the right sender according to the Unified semantics,
840 -- TODO: this is the right sender according to the Unified semantics,
609 -- but perhaps having 'them' as the sender would make more sense
841 -- but perhaps having 'them' as the sender would make more sense
610 -- (see also: notifyDied)
842 -- (see also: notifyDied)
611− liftIO $ sendBinary node
612− (NodeIdentifier $ localNodeId node)
613− (NodeIdentifier $ processNodeId from)
843+ ncSendToNode (processNodeId from) $ NCMsg
614− WithImplicitReconnect
616− { ctrlMsgSender = NodeIdentifier (localNodeId node)
844+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
617− , ctrlMsgSignal = Died them DiedUnknownId
845+ , ctrlMsgSignal = Died them DiedUnknownId
620-- [Unified: Table 11]
848-- [Unified: Table 11]
621ncEffectUnlink :: ProcessId -> Identifier -> NC ()
849ncEffectUnlink :: ProcessId -> Identifier -> NC ()
@@ -629,7 +857,7 @@ ncEffectUnlink from them = do
629 postAsMessage from $ DidUnlinkNode nid
857 postAsMessage from $ DidUnlinkNode nid
630 SendPortIdentifier cid ->
858 SendPortIdentifier cid ->
631 postAsMessage from $ DidUnlinkPort cid
859 postAsMessage from $ DidUnlinkPort cid
632− modify' $ linksFor them ^: Set.delete from
860+ modify' $ links ^: BiMultiMap.delete them from ()
634-- [Unified: Table 11]
862-- [Unified: Table 11]
635ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
863ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
@@ -637,7 +865,7 @@ ncEffectUnmonitor from ref = do
637 node <- ask
865 node <- ask
638 when (isLocal node (ProcessIdentifier from)) $
866 when (isLocal node (ProcessIdentifier from)) $
639 postAsMessage from $ DidUnmonitor ref
867 postAsMessage from $ DidUnmonitor ref
640− modify' $ monitorsFor (monitorRefIdent ref) ^: Set.delete (from, ref)
868+ modify' $ monitors ^: BiMultiMap.delete (monitorRefIdent ref) from ref
642-- [Unified: Table 12]
870-- [Unified: Table 12]
643ncEffectDied :: Identifier -> DiedReason -> NC ()
871ncEffectDied :: Identifier -> DiedReason -> NC ()
@@ -652,7 +880,7 @@ ncEffectDied ident reason = do
652 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
880 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
654 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
882 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
655− forM_ uss $ \us ->
883+ forM_ uss $ \(us, _) ->
656 when (localOnly <= isLocal node (ProcessIdentifier us)) $
884 when (localOnly <= isLocal node (ProcessIdentifier us)) $
657 notifyDied us them reason Nothing
885 notifyDied us them reason Nothing
@@ -661,9 +889,35 @@ ncEffectDied ident reason = do
661 when (localOnly <= isLocal node (ProcessIdentifier us)) $
889 when (localOnly <= isLocal node (ProcessIdentifier us)) $
662 notifyDied us them reason (Just ref)
890 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
664− modify' $ (links ^= unaffectedLinks) . (monitors ^= unaffectedMons)
914+ modify' $ (links ^= unaffectedLinks') . (monitors ^= unaffectedMons')
916+ -- we now consider all labels for this identifier unregistered
666− modify' $ registeredHere ^: Map.filter (\pid -> not $ ident `impliesDeathOf` ProcessIdentifier pid)
917+ let toDrop 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
668 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
922 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
669 mapM (\(pid,nidlist) ->
923 mapM (\(pid,nidlist) ->
@@ -671,20 +925,15 @@ ncEffectDied ident reason = do
672 do forM_ nidlist $ \(nid,_) ->
926 do forM_ nidlist $ \(nid,_) ->
673 when (not $ isLocal node (NodeIdentifier nid))
927 when (not $ isLocal node (NodeIdentifier nid))
674− (forwardNameDeath node nid)
928+ (forwardDeath node nid)
675 return Nothing
929 return Nothing
676 False -> return $ Just (pid,nidlist) )
930 False -> return $ Just (pid,nidlist) )
677 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
931 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
679− forwardNameDeath node nid =
933+ forwardDeath node nid = ncSendToNode nid
680− liftIO $ sendBinary node
681− (NodeIdentifier $ localNodeId node)
682− (NodeIdentifier $ nid)
683− WithImplicitReconnect
685− { ctrlMsgSender = NodeIdentifier (localNodeId node)
934+ NCMsg { ctrlMsgSender = NodeIdentifier (localNodeId node)
686− , ctrlMsgSignal = Died ident reason
935+ , ctrlMsgSignal = Died ident reason
689-- [Unified: Table 13]
938-- [Unified: Table 13]
690ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
939ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
@@ -692,16 +941,13 @@ ncEffectSpawn pid cProc ref = do
692 mProc <- unClosure cProc
941 mProc <- unClosure cProc
693 -- If the closure does not exist, we spawn a process that throws an exception
942 -- If the closure does not exist, we spawn a process that throws an exception
694 -- This allows the remote node to find out what's happening
943 -- This allows the remote node to find out what's happening
695 let proc = case mProc of
945 let proc = case mProc of
696 Left err -> fail $ "Error: Could not resolve closure: " ++ err
946 Left err -> fail $ "Error: Could not resolve closure: " ++ err
697 Right p -> p
947 Right p -> p
698 node <- ask
948 node <- ask
699 pid' <- liftIO $ forkProcess node proc
949 pid' <- liftIO $ forkProcess node proc
700− liftIO $ sendMessage node
950+ ncSendToProcess pid $ unsafeCreateUnencodedMessage $ DidSpawn ref pid'
701− (NodeIdentifier (localNodeId node))
702− (ProcessIdentifier pid)
703− WithImplicitReconnect
706-- Unified semantics does not explicitly describe how to implement 'register',
952-- Unified semantics does not explicitly describe how to implement 'register',
707-- but mentions it's "very similar to nsend" (Table 14)
953-- but mentions it's "very similar to nsend" (Table 14)
@@ -719,14 +965,19 @@ ncEffectRegister from label atnode mPid reregistration = do
719 return $ (isNothing currentVal /= reregistration) &&
965 return $ (isNothing currentVal /= reregistration) &&
720 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
966 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
721 if isLocal node (NodeIdentifier atnode)
967 if isLocal node (NodeIdentifier atnode)
722− then do when (isOk) $
968+ then do when isOk $
723 do modify' $ registeredHereFor label ^= mPid
969 do modify' $ registeredHereFor label ^= mPid
724 updateRemote node currentVal mPid
970 updateRemote node currentVal mPid
725− liftIO $ sendMessage node
971+ case mPid of
726− (NodeIdentifier (localNodeId node))
972+ (Just p) -> do
727− (ProcessIdentifier from)
973+ if reregistration
728− WithImplicitReconnect
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)
978+ newVal <- gets (^. registeredHereFor label)
979+ ncSendToProcess from $ unsafeCreateUnencodedMessage $
729− (RegisterReply label isOk)
980+ RegisterReply label isOk newVal
730 else let operation =
981 else let operation =
731 case reregistration of
982 case reregistration of
732 True -> flip decList
983 True -> flip decList
@@ -744,6 +995,7 @@ ncEffectRegister from label atnode mPid reregistration = do
744 updateRemote _ _ _ = return ()
995 updateRemote _ _ _ = return ()
745 maybeify f Nothing = unmaybeify $ f []
996 maybeify f Nothing = unmaybeify $ f []
746 maybeify f (Just x) = unmaybeify $ f x
997 maybeify f (Just x) = unmaybeify $ f x
747 unmaybeify [] = Nothing
999 unmaybeify [] = Nothing
748 unmaybeify x = Just x
1000 unmaybeify x = Just x
749 incList [] tag = [(tag,1)]
1001 incList [] tag = [(tag,1)]
@@ -755,39 +1007,61 @@ ncEffectRegister from label atnode mPid reregistration = do
755 decList (x:xs) tag = x:decList xs tag
1007 decList (x:xs) tag = x:decList xs tag
756 forward node to reg =
1008 forward node to reg =
757 when (not $ isLocal node (NodeIdentifier to)) $
1009 when (not $ isLocal node (NodeIdentifier to)) $
758− liftIO $ sendBinary node
759− (ProcessIdentifier from)
761− WithImplicitReconnect
763− { ctrlMsgSender = ProcessIdentifier from
1010+ ncSendToNode to $ NCMsg { ctrlMsgSender = ProcessIdentifier from
764− , ctrlMsgSignal = reg
1011+ , ctrlMsgSignal = reg
768-- Unified semantics does not explicitly describe 'whereis'
1015-- Unified semantics does not explicitly describe 'whereis'
769ncEffectWhereIs :: ProcessId -> String -> NC ()
1016ncEffectWhereIs :: ProcessId -> String -> NC ()
770ncEffectWhereIs from label = do
1017ncEffectWhereIs from label = do
772 mPid <- gets (^. registeredHereFor label)
1018 mPid <- gets (^. registeredHereFor label)
773− liftIO $ sendMessage node
774− (NodeIdentifier (localNodeId node))
775− (ProcessIdentifier from)
776− WithImplicitReconnect
777− (WhereIsReply label mPid)
1019+ ncSendToProcess from $ unsafeCreateUnencodedMessage $ WhereIsReply label mPid
779-- [Unified: Table 14]
1021-- [Unified: Table 14]
780−ncEffectNamedSend :: Identifier -> String -> Message -> NC ()
1022+ncEffectNamedSend :: String -> Message -> NC ()
781−ncEffectNamedSend from label msg = do
1023+ncEffectNamedSend label msg = do
783 mPid <- gets (^. registeredHereFor label)
1024 mPid <- gets (^. registeredHereFor label)
784 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
1025 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
785− forM_ mPid $ \pid ->
1026+ forM_ mPid $ \to ->
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
1032+ncEffectLocalSend :: LocalNode -> ProcessId -> Message -> NC ()
1033+ncEffectLocalSend = ncEffectLocalSendAndTrace True
1035+ncEffectLocalSendAndTrace :: Bool -> LocalNode -> ProcessId -> Message -> NC ()
1036+ncEffectLocalSendAndTrace shouldTrace node to msg =
786− liftIO $ sendPayload node
1037+ liftIO $ withLocalProc node to $ \p -> do
787− from
1038+ enqueue (processQueue p) msg
788− (ProcessIdentifier pid)
1039+ when shouldTrace $ trace node (MxReceived to msg)
789− NoImplicitReconnect
1040+
790− (messageToPayload msg)
1041+-- [Issue #DP-20]
1042+ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
1043+ncEffectLocalPortSend from msg = do
1045+ let pid = sendPortProcessId from
1046+ cid = sendPortLocalId from
1047+ liftIO $ withLocalProc node pid $ \proc -> do
1048+ mChan <- withMVar (processState proc) $ return . (^. typedChannelWithId cid)
1050+ -- in the unlikely event we know nothing about this channel id,
1051+ -- there's little to be done - perhaps some logging/tracing though...
1052+ Nothing -> return ()
1053+ Just (TypedChannel chan') -> do
1054+ -- If ch is Nothing, the process has given up the read end of
1055+ -- the channel and we simply ignore the incoming message - this
1056+ ch <- deRefWeak chan'
1057+ forM_ ch $ \chan -> deliverChan node from msg chan
1058+ where deliverChan :: forall a . LocalNode -> SendPortId -> Message -> TQueue a -> IO ()
1059+ deliverChan n p (UnencodedMessage _ raw) chan' = do
1060+ atomically $ writeTQueue chan' ((unsafeCoerce raw) :: a)
1061+ trace n (MxReceivedPort p $ unsafeCreateUnencodedMessage raw)
1062+ deliverChan _ _ (EncodedMessage _ _) _ =
1063+ -- this will not happen unless someone screws with Primitives.hs
1064+ error "invalid local channel delivery"
792-- [Issue #69]
1066-- [Issue #69]
793ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
1067ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
@@ -810,46 +1084,56 @@ ncEffectGetInfo from pid =
810 them = (ProcessIdentifier pid)
1084 them = (ProcessIdentifier pid)
812 node <- ask
1086 node <- ask
813− mProc <- liftIO $
1087+ mProc <- liftIO $ withValidLocalState node
814− withMVar (localState node) $ return . (^. localProcessWithId lpid)
1088+ $ return . (^. localProcessWithId lpid)
815 case mProc of
1089 case mProc of
816 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
1090 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
817− from node (ProcessInfoNone DiedUnknownId)
1091+ from (ProcessInfoNone DiedUnknownId)
818− Just _ -> do
1092+ Just proc -> do
819− itsLinks <- gets (^. linksFor them)
1093+ itsLinks <- Set.map fst . BiMultiMap.lookupBy1st them <$>
820− itsMons <- gets (^. monitorsFor them)
1094+ gets (^. links)
1095+ itsMons <- BiMultiMap.lookupBy1st them <$> gets (^. monitors)
821 registered <- gets (^. registeredHere)
1096 registered <- gets (^. registeredHere)
1097+ size <- liftIO $ queueSize $ processQueue $ proc
823 let reg = registeredNames registered
1099 let reg = registeredNames registered
824 dispatch (isLocal node (ProcessIdentifier from))
1100 dispatch (isLocal node (ProcessIdentifier from))
827 ProcessInfo {
1102 ProcessInfo {
828 infoNode = (processNodeId pid)
1103 infoNode = (processNodeId pid)
829 , infoRegisteredNames = reg
1104 , infoRegisteredNames = reg
830− -- we cannot populate this field
831− , infoMessageQueueLength = Nothing
1105+ , infoMessageQueueLength = size
832− , infoMonitors = Set.toList itsMons
1106+ , infoMonitors = Set.toList itsMons
833− , infoLinks = Set.toList itsLinks
1107+ , infoLinks = Set.toList itsLinks
835− where dispatch :: (Serializable a, Show a)
1109+ where dispatch :: (Serializable a)
837 -> ProcessId
1111 -> ProcessId
840 -> NC ()
1113 -> NC ()
841− dispatch True dest _ pInfo = postAsMessage dest $ pInfo
1114+ dispatch True dest pInfo = postAsMessage dest $ pInfo
842− dispatch False dest node pInfo = do
1115+ dispatch False dest pInfo =
843− liftIO $ sendMessage node
1116+ ncSendToProcess dest $ unsafeCreateUnencodedMessage pInfo
844− (NodeIdentifier (localNodeId node))
845− (ProcessIdentifier dest)
846− WithImplicitReconnect
849 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
1118 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
850 then (k:ks)
1119 then (k:ks)
851 else ks) []
1120 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
853--------------------------------------------------------------------------------
1137--------------------------------------------------------------------------------
854-- Auxiliary --
1138-- Auxiliary --
855--------------------------------------------------------------------------------
1139--------------------------------------------------------------------------------
@@ -876,32 +1160,33 @@ notifyDied dest src reason mRef = do
876 throwException dest $ PortLinkException pid reason
1160 throwException dest $ PortLinkException pid reason
877 (False, _, _) ->
1161 (False, _, _) ->
878 -- The change in sender comes from [Unified: Table 10]
1162 -- The change in sender comes from [Unified: Table 10]
879− liftIO $ sendBinary node
880− (NodeIdentifier $ localNodeId node)
881− (NodeIdentifier $ processNodeId dest)
1163+ ncSendToNode (processNodeId dest) $ NCMsg
882− WithImplicitReconnect
884− { ctrlMsgSender = NodeIdentifier (localNodeId node)
1164+ { ctrlMsgSender = NodeIdentifier (localNodeId node)
885− , ctrlMsgSignal = Died src reason
1165+ , ctrlMsgSignal = Died src reason
888-- | [Unified: Table 8]
1168-- | [Unified: Table 8]
889destNid :: ProcessSignal -> Maybe NodeId
1169destNid :: ProcessSignal -> Maybe NodeId
890−destNid (Link ident) = Just $ nodeOf ident
1170+destNid (Link ident) = Just $ nodeOf ident
891−destNid (Unlink ident) = Just $ nodeOf ident
1171+destNid (Unlink ident) = Just $ nodeOf ident
892−destNid (Monitor ref) = Just $ nodeOf (monitorRefIdent ref)
1172+destNid (Monitor ref) = Just $ nodeOf (monitorRefIdent ref)
893−destNid (Unmonitor ref) = Just $ nodeOf (monitorRefIdent ref)
1173+destNid (Unmonitor ref) = Just $ nodeOf (monitorRefIdent ref)
894−destNid (Spawn _ _) = Nothing
1174+destNid (Spawn _ _) = Nothing
895−destNid (Register _ _ _ _) = Nothing
1175+destNid (Register _ _ _ _) = Nothing
896−destNid (WhereIs _) = Nothing
1176+destNid (WhereIs _) = Nothing
897−destNid (NamedSend _ _) = Nothing
1177+destNid (NamedSend _ _) = Nothing
1178+destNid (UnreliableSend _ _) = Nothing
898-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
1179-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
899-- then when a local process dies the monitoring/linking machinery will take
1180-- then when a local process dies the monitoring/linking machinery will take
900-- care of notifying remote nodes
1181-- care of notifying remote nodes
901−destNid (Died _ _) = Nothing
1182+destNid (Died _ _) = Nothing
902−destNid (Kill pid _) = Just $ processNodeId pid
1183+destNid (Kill pid _) = Just $ processNodeId pid
903−destNid (Exit pid _) = Just $ processNodeId pid
1184+destNid (Exit pid _) = Just $ processNodeId pid
904−destNid (GetInfo pid) = Just $ processNodeId pid
1185+destNid (GetInfo pid) = Just $ processNodeId pid
1186+destNid (GetNodeStats nid) = Just nid
1187+destNid (LocalSend pid _) = Just $ processNodeId pid
1188+destNid (LocalPortSend cid _) = Just $ processNodeId (sendPortProcessId cid)
1189+destNid (SigShutdown) = Nothing
906-- | Check if a process is local to our own node
1191-- | Check if a process is local to our own node
907isLocal :: LocalNode -> Identifier -> Bool
1192isLocal :: LocalNode -> Identifier -> Bool
@@ -917,7 +1202,7 @@ unClosure closure = do
917isValidLocalIdentifier :: Identifier -> NC Bool
1202isValidLocalIdentifier :: Identifier -> NC Bool
918isValidLocalIdentifier ident = do
1203isValidLocalIdentifier ident = do
919 node <- ask
1204 node <- ask
920− liftIO . withMVar (localState node) $ \nSt ->
1205+ liftIO . withValidLocalState node $ \nSt ->
921 case ident of
1206 case ident of
922 NodeIdentifier nid ->
1207 NodeIdentifier nid ->
923 return $ nid == localNodeId node
1208 return $ nid == localNodeId node
@@ -938,34 +1223,37 @@ isValidLocalIdentifier ident = do
938--------------------------------------------------------------------------------
1223--------------------------------------------------------------------------------
940postAsMessage :: Serializable a => ProcessId -> a -> NC ()
1225postAsMessage :: Serializable a => ProcessId -> a -> NC ()
941−postAsMessage pid = postMessage pid . createMessage
1226+postAsMessage pid = postMessage pid . createUnencodedMessage
943postMessage :: ProcessId -> Message -> NC ()
1228postMessage :: ProcessId -> Message -> NC ()
944postMessage pid msg = do
1229postMessage pid msg = do
945− withLocalProc pid $ \p -> enqueue (processQueue p) msg
1231+ liftIO $ withLocalProc node pid $ \p -> enqueue (processQueue p) msg
947throwException :: Exception e => ProcessId -> e -> NC ()
1233throwException :: Exception e => ProcessId -> e -> NC ()
948−throwException pid e = withLocalProc pid $ \p ->
1234+throwException pid e = do
949− throwTo (processThread p) e
951−withLocalProc :: ProcessId -> (LocalProcess -> IO ()) -> NC ()
952−withLocalProc pid p = do
953 node <- ask
1235 node <- ask
954− liftIO $ do
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
1241+withLocalProc :: LocalNode -> ProcessId -> (LocalProcess -> IO ()) -> IO ()
1242+withLocalProc node pid p =
955− -- By [Unified: table 6, rule missing_process] messages to dead processes
1243+ -- By [Unified: table 6, rule missing_process] messages to dead processes
956− -- can silently be dropped
1244+ -- can silently be dropped
957− let lpid = processLocalId pid
1245+ let lpid = processLocalId pid in do
1246+ join $ withValidLocalState node $ \vst ->
958− mProc <- withMVar (localState node) $ return . (^. localProcessWithId lpid)
1247+ return $ forM_ (vst ^. localProcessWithId lpid) p
961--------------------------------------------------------------------------------
1249--------------------------------------------------------------------------------
962-- Accessors --
1250-- Accessors --
963--------------------------------------------------------------------------------
1251--------------------------------------------------------------------------------
965−links :: Accessor NCState (Map Identifier (Set ProcessId))
1253+links :: Accessor NCState (BiMultiMap Identifier ProcessId ())
966links = accessor _links (\ls st -> st { _links = ls })
1254links = accessor _links (\ls st -> st { _links = ls })
968−monitors :: Accessor NCState (Map Identifier (Set (ProcessId, MonitorRef)))
1256+monitors :: Accessor NCState (BiMultiMap Identifier ProcessId MonitorRef)
969monitors = accessor _monitors (\ms st -> st { _monitors = ms })
1257monitors = accessor _monitors (\ms st -> st { _monitors = ms })
971registeredHere :: Accessor NCState (Map String ProcessId)
1259registeredHere :: Accessor NCState (Map String ProcessId)
@@ -974,12 +1262,6 @@ registeredHere = accessor _registeredHere (\ry st -> st { _registeredHere = ry }
974registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
1262registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
975registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
1263registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
977−linksFor :: Identifier -> Accessor NCState (Set ProcessId)
978−linksFor ident = links >>> DAC.mapDefault Set.empty ident
980−monitorsFor :: Identifier -> Accessor NCState (Set (ProcessId, MonitorRef))
981−monitorsFor ident = monitors >>> DAC.mapDefault Set.empty ident
983registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
1265registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
984registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
1266registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
@@ -1006,10 +1288,12 @@ registeredOnNodesFor ident = registeredOnNodes >>> DAC.mapMaybe ident
1006-- * the notifications for typed channels to that process.
1288-- * the notifications for typed channels to that process.
1008-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1290-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1291+splitNotif :: (Ord a, Ord v)
1009−splitNotif :: Identifier
1292+ => Identifier
1010− -> Map Identifier a
1293+ -> BiMultiMap Identifier a v
1011− -> (Map Identifier a, Map Identifier a)
1294+ -> (Map Identifier (Set (a,v)), BiMultiMap Identifier a v)
1012−splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1295+splitNotif ident =
1296+ BiMultiMap.partitionWithKeyBy1st (\k !_v -> ident `impliesDeathOf` k)
1014--------------------------------------------------------------------------------
1298--------------------------------------------------------------------------------
1015-- Auxiliary --
1299-- Auxiliary --