git.iko.soy/distributed-process
on 35e2788 help sign in
1233 lines 49 kB history raw
1{-# LANGUAGE CPP #-}
2{-# LANGUAGE DeriveDataTypeable #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE RankNTypes #-}
5{-# LANGUAGE BangPatterns #-}
6{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7{-# LANGUAGE RecordWildCards #-}
9-- | Local nodes
10--
11module Control.Distributed.Process.Node
12 ( LocalNode
13 , newLocalNode
14 , closeLocalNode
15 , forkProcess
16 , runProcess
17 , initRemoteTable
18 , localNodeId
19 ) where
21-- TODO: Calls to 'sendBinary' and co (by the NC) may stall the node controller.
23#if ! MIN_VERSION_base(4,6,0)
24import Prelude hiding (catch)
25#endif
27import System.IO (fixIO, hPutStrLn, stderr)
28import System.Mem.Weak (Weak, deRefWeak)
29import qualified Data.ByteString.Lazy as BSL (fromChunks)
30import Data.Binary (decode)
31import Data.Map (Map)
32import qualified Data.Map as Map
33 ( empty
34 , toList
35 , fromList
36 , filter
37 , partitionWithKey
38 , elems
39 , size
40 , filterWithKey
41 , foldlWithKey
42 )
43import Data.Set (Set)
44import qualified Data.Set as Set
45 ( empty
46 , insert
47 , delete
48 , member
49 , toList
50 )
51import Data.Foldable (forM_)
52import Data.Maybe (isJust, fromJust, isNothing, catMaybes)
53import Data.Typeable (Typeable)
54import Control.Category ((>>>))
55import Control.Applicative (Applicative, (<$>))
56import Control.Monad (void, when)
57import Control.Monad.IO.Class (MonadIO, liftIO)
58import Control.Monad.State.Strict (MonadState, StateT, evalStateT, gets)
59import qualified Control.Monad.State.Strict as StateT (get, put)
60import Control.Monad.Reader (MonadReader, ReaderT, runReaderT, ask)
61import Control.Exception
62 ( throwIO
63 , AsyncException(ThreadKilled)
64 , SomeException
65 , Exception
66 , throwTo
67 , uninterruptibleMask_
68 )
69import qualified Control.Exception as Exception (Handler(..), catches, finally)
70import Control.Concurrent (forkIO, forkIOWithUnmask, killThread, myThreadId)
71import Control.Distributed.Process.Internal.StrictMVar
72 ( newMVar
73 , withMVar
74 , modifyMVarMasked
75 , modifyMVar_
76 , newEmptyMVar
77 , putMVar
78 , takeMVar
79 )
80import Control.Concurrent.Chan (newChan, writeChan, readChan)
81import qualified Control.Concurrent.MVar as MVar (newEmptyMVar, takeMVar)
82import Control.Concurrent.STM
83 ( atomically
84 )
85import Control.Distributed.Process.Internal.CQueue
86 ( CQueue
87 , enqueue
88 , newCQueue
89 , mkWeakCQueue
90 , queueSize
91 )
92import qualified Network.Transport as NT
93 ( Transport
94 , EndPoint
95 , newEndPoint
96 , receive
97 , Event(..)
98 , EventErrorCode(..)
99 , TransportError(..)
100 , address
101 , closeEndPoint
102 , Connection
103 , ConnectionId
104 , close
105 , EndPointAddress
106 , Reliability(ReliableOrdered)
107 )
108import Data.Accessor (Accessor, accessor, (^.), (^=), (^:))
109import System.Random (randomIO)
110import Control.Distributed.Static (RemoteTable, Closure)
111import qualified Control.Distributed.Static as Static
112 ( unclosure
113 , initRemoteTable
114 )
115import Control.Distributed.Process.Internal.Types
116 ( NodeId(..)
117 , LocalProcessId(..)
118 , ProcessId(..)
119 , LocalNode(..)
120 , MxEventBus(..)
121 , LocalNodeState(..)
122 , ValidLocalNodeState(..)
123 , withValidLocalState
124 , modifyValidLocalState
125 , LocalProcess(..)
126 , LocalProcessState(..)
127 , Process(..)
128 , DiedReason(..)
129 , NCMsg(..)
130 , ProcessSignal(..)
131 , localPidCounter
132 , localPidUnique
133 , localProcessWithId
134 , localProcesses
135 , localConnections
136 , forever'
137 , MonitorRef(..)
138 , ProcessMonitorNotification(..)
139 , NodeMonitorNotification(..)
140 , PortMonitorNotification(..)
141 , ProcessExitException(..)
142 , ProcessLinkException(..)
143 , NodeLinkException(..)
144 , PortLinkException(..)
145 , DidUnmonitor(..)
146 , DidUnlinkProcess(..)
147 , DidUnlinkNode(..)
148 , DidUnlinkPort(..)
149 , SpawnRef
150 , DidSpawn(..)
151 , Message(..)
152 , TypedChannel(..)
153 , Identifier(..)
154 , nodeOf
155 , ProcessInfo(..)
156 , ProcessInfoNone(..)
157 , NodeStats(..)
158 , SendPortId(..)
159 , typedChannelWithId
160 , RegisterReply(..)
161 , WhereIsReply(..)
162 , payloadToMessage
163 , messageToPayload
164 , createUnencodedMessage
165 , runLocalProcess
166 , firstNonReservedProcessId
167 , ImplicitReconnect(WithImplicitReconnect,NoImplicitReconnect)
168 )
169import Control.Distributed.Process.Management.Internal.Agent
170 ( mxAgentController
171 )
172import qualified Control.Distributed.Process.Management.Internal.Table as Table
173 ( mxTableCoordinator
174 , startTableCoordinator
175 )
176import qualified Control.Distributed.Process.Management.Internal.Trace.Remote as Trace
177 ( remoteTable
178 )
179import Control.Distributed.Process.Management.Internal.Trace.Tracer
180 ( defaultTracer
181 )
182import Control.Distributed.Process.Management.Internal.Trace.Types
183 ( TraceArg(..)
184 , traceEvent
185 , traceLogFmt
186 , enableTrace
187 )
188import Control.Distributed.Process.Management.Internal.Types
189 ( MxEvent(..)
190 )
191import Control.Distributed.Process.Serializable (Serializable)
192import Control.Distributed.Process.Internal.Messaging
193 ( sendBinary
194 , sendMessage
195 , sendPayload
196 , closeImplicitReconnections
197 , impliesDeathOf
198 )
199import Control.Distributed.Process.Internal.Primitives
200 ( register
201 , finally
202 , receiveWait
203 , match
204 , sendChan
205 , catch
206 , unwrapMessage
207 )
208import Control.Distributed.Process.Internal.Types (SendPort, Tracer(..))
209import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
210import Control.Distributed.Process.Internal.WeakTQueue (TQueue, writeTQueue)
211import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
212 ( mapMaybe
213 , mapDefault
214 )
215import Unsafe.Coerce
217--------------------------------------------------------------------------------
218-- Initialization --
219--------------------------------------------------------------------------------
221initRemoteTable :: RemoteTable
222initRemoteTable = Trace.remoteTable $ BuiltIn.remoteTable Static.initRemoteTable
224-- | Initialize a new local node.
225newLocalNode :: NT.Transport -> RemoteTable -> IO LocalNode
226newLocalNode transport rtable = do
227 mEndPoint <- NT.newEndPoint transport
228 case mEndPoint of
229 Left ex -> throwIO ex
230 Right endPoint -> do
231 localNode <- createBareLocalNode endPoint rtable
232 startServiceProcesses localNode
233 return localNode
235-- | Create a new local node (without any service processes running)
236createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
237createBareLocalNode endPoint rtable = do
238 unq <- randomIO
239 state <- newMVar $ LocalNodeValid $ ValidLocalNodeState
240 { _localProcesses = Map.empty
241 , _localPidCounter = firstNonReservedProcessId
242 , _localPidUnique = unq
243 , _localConnections = Map.empty
244 }
245 ctrlChan <- newChan
246 let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
247 , localEndPoint = endPoint
248 , localState = state
249 , localCtrlChan = ctrlChan
250 , localEventBus = MxEventBusInitialising
251 , remoteTable = rtable
252 }
253 tracedNode <- startMxAgent node
255 -- Once the NC terminates, the endpoint isn't much use,
256 void $ forkIO $ Exception.finally (runNodeController tracedNode)
257 (NT.closeEndPoint (localEndPoint node))
259 -- whilst a closed/failing endpoint will terminate the NC
260 void $ forkIO $ Exception.finally (handleIncomingMessages tracedNode)
261 (stopNC node)
263 return tracedNode
264 where
265 stopNC node =
266 writeChan (localCtrlChan node) NCMsg
267 { ctrlMsgSender = NodeIdentifier (localNodeId node)
268 , ctrlMsgSignal = SigShutdown
269 }
271startMxAgent :: LocalNode -> IO LocalNode
272startMxAgent node = do
273 -- see note [tracer/forkProcess races]
274 let fork = forkProcess node
275 mv <- MVar.newEmptyMVar
276 pid <- fork $ mxAgentController fork mv
277 (tracer', wqRef, mxNew') <- MVar.takeMVar mv
278 return node { localEventBus = (MxEventBus pid tracer' wqRef mxNew') }
280startDefaultTracer :: LocalNode -> IO ()
281startDefaultTracer node' = do
282 let t = localEventBus node'
283 case t of
284 MxEventBus _ (Tracer pid _) _ _ -> do
285 runProcess node' $ register "trace.controller" pid
286 pid' <- forkProcess node' defaultTracer
287 enableTrace (localEventBus node') pid'
288 runProcess node' $ register "tracer.initial" pid'
289 _ -> return ()
291-- TODO: we need a better mechanism for defining and registering services
293-- | Start and register the service processes on a node
294startServiceProcesses :: LocalNode -> IO ()
295startServiceProcesses node = do
296 -- tracing /spawns/ relies on the tracer being enabled, but we start
297 -- the default tracer first, even though it might @nsend@ to the logger
298 -- before /that/ process has started - this is a totally harmless race
299 -- however, so we deliberably ignore it
300 startDefaultTracer node
301 tableCoordinatorPid <- fork $ Table.startTableCoordinator fork
302 runProcess node $ register Table.mxTableCoordinator tableCoordinatorPid
303 logger <- forkProcess node loop
304 runProcess node $ do
305 register "logger" logger
306 -- The trace.logger is used for tracing to the console to avoid feedback
307 -- loops during tracing if the user reregisters the "logger" with a custom
308 -- process which uses 'send' or other primitives which are traced.
309 register "trace.logger" logger
310 where
311 fork = forkProcess node
313 loop = do
314 receiveWait
315 [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
316 liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
317 loop
318 , match $ \((time, string) :: (String, String)) -> do
319 -- this is a 'trace' message from the local node tracer
320 liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
321 loop
322 , match $ \(ch :: SendPort ()) -> -- a shutdown request
323 sendChan ch ()
324 ]
326-- | Force-close a local node, killing all processes on that node.
327closeLocalNode :: LocalNode -> IO ()
328closeLocalNode node = do
329 modifyMVar_ (localState node) $ \st -> case st of
330 LocalNodeValid vst -> do
331 forM_ (vst ^. localProcesses) $ \lproc ->
332 -- Semantics of 'throwTo' guarantee that target thread will get
333 -- delivered an exception. Therefore, target thread will be killed
334 -- eventually and that's as good as we can do. No need to wait for
335 -- thread to actually finish dying.
336 killThread (processThread lproc)
337 return LocalNodeClosed
338 LocalNodeClosed -> return LocalNodeClosed
339 -- This call will have the effect of shutting down the NC as well (see
340 -- 'createBareLocalNode').
341 NT.closeEndPoint (localEndPoint node)
343-- | Run a process on a local node and wait for it to finish
344runProcess :: LocalNode -> Process () -> IO ()
345runProcess node proc = do
346 done <- newEmptyMVar
347 tid <- myThreadId
348 void $ forkProcess node $ do
349 catch (proc `finally` liftIO (putMVar done ()))
350 (\(ex :: SomeException) -> liftIO $ throwTo tid ex)
351 takeMVar done
353-- | Spawn a new process on a local node
354forkProcess :: LocalNode -> Process () -> IO ProcessId
355forkProcess node proc =
356 modifyMVarMasked (localState node) startProcess
357 where
358 startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
359 startProcess (LocalNodeValid vst) = do
360 let lpid = LocalProcessId { lpidCounter = vst ^. localPidCounter
361 , lpidUnique = vst ^. localPidUnique
362 }
363 let pid = ProcessId { processNodeId = localNodeId node
364 , processLocalId = lpid
365 }
366 pst <- newMVar LocalProcessState { _monitorCounter = 0
367 , _spawnCounter = 0
368 , _channelCounter = 0
369 , _typedChannels = Map.empty
370 }
371 queue <- newCQueue
372 weakQueue <- mkWeakCQueue queue (return ())
373 (_, lproc) <- fixIO $ \ ~(tid, _) -> do
374 let lproc = LocalProcess { processQueue = queue
375 , processWeakQ = weakQueue
376 , processId = pid
377 , processState = pst
378 , processThread = tid
379 , processNode = node
380 }
381 tid' <- uninterruptibleMask_ $ forkIOWithUnmask $ \unmask -> do
382 reason <- Exception.catches
383 (unmask $ runLocalProcess lproc proc >> return DiedNormal)
384 [ (Exception.Handler (\ex@(ProcessExitException from msg) -> do
385 mMsg <- unwrapMessage msg :: IO (Maybe String)
386 case mMsg of
387 Nothing -> return $ DiedException $ show ex
388 Just m -> return $ DiedException ("exit-from=" ++ (show from) ++ ",reason=" ++ m)))
389 , (Exception.Handler
390 (return . DiedException . (show :: SomeException -> String)))]
392 -- [Unified: Table 4, rules termination and exiting]
393 mconns <- modifyValidLocalState node (cleanupProcess pid)
394 -- XXX: Revisit after agreeing on the bigger picture for the semantics
395 -- of transport operations.
396 -- https://github.com/haskell-distributed/distributed-process/issues/204
397 forM_ mconns $ forkIO . mapM_ NT.close
399 writeChan (localCtrlChan node) NCMsg
400 { ctrlMsgSender = ProcessIdentifier pid
401 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
402 }
403 return (tid', lproc)
405 -- see note [tracer/forkProcess races]
406 trace node (MxSpawned pid)
408 if lpidCounter lpid == maxBound
409 then do
410 -- TODO: this doesn't look right at all - how do we know
411 -- that newUnique represents a process id that is available!?
412 newUnique <- randomIO
413 return ( LocalNodeValid
414 $ (localProcessWithId lpid ^= Just lproc)
415 . (localPidCounter ^= firstNonReservedProcessId)
416 . (localPidUnique ^= newUnique)
417 $ vst
418 , pid
419 )
420 else
421 return ( LocalNodeValid
422 $ (localProcessWithId lpid ^= Just lproc)
423 . (localPidCounter ^: (+ 1))
424 $ vst
425 , pid
426 )
427 startProcess LocalNodeClosed = throwIO $ userError $ "Node closed " ++ show (localNodeId node)
429 cleanupProcess :: ProcessId
430 -> ValidLocalNodeState
431 -> IO (ValidLocalNodeState, [NT.Connection])
432 cleanupProcess pid vst = do
433 let pid' = ProcessIdentifier pid
434 let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (vst ^. localConnections)
435 return ( (localProcessWithId (processLocalId pid) ^= Nothing)
436 . (localConnections ^= unaffected)
437 $ vst
438 , map fst $ Map.elems affected
439 )
441-- note [tracer/forkProcess races]
442--
443-- Our startTracing function uses forkProcess to start the trace controller
444-- process, and of course forkProcess attempts to call traceEvent once the
445-- process has started. This is harmless, as the localEventBus is not updated
446-- until /after/ the initial forkProcess completes, so the first call to
447-- traceEvent behaves as if tracing were disabled (i.e., it is ignored).
448--
450--------------------------------------------------------------------------------
451-- Handle incoming messages --
452--------------------------------------------------------------------------------
454type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
456data IncomingTarget =
457 Uninit
458 | ToProc ProcessId (Weak (CQueue Message))
459 | ToChan TypedChannel
460 | ToNode
462data ConnectionState = ConnectionState {
463 _incoming :: !(Map NT.ConnectionId IncomingConnection)
464 , _incomingFrom :: !(Map NT.EndPointAddress (Set NT.ConnectionId))
465 }
467initConnectionState :: ConnectionState
468initConnectionState = ConnectionState {
469 _incoming = Map.empty
470 , _incomingFrom = Map.empty
471 }
473incoming :: Accessor ConnectionState (Map NT.ConnectionId IncomingConnection)
474incoming = accessor _incoming (\conns st -> st { _incoming = conns })
476incomingAt :: NT.ConnectionId -> Accessor ConnectionState (Maybe IncomingConnection)
477incomingAt cid = incoming >>> DAC.mapMaybe cid
479incomingFrom :: NT.EndPointAddress -> Accessor ConnectionState (Set NT.ConnectionId)
480incomingFrom addr = aux >>> DAC.mapDefault Set.empty addr
481 where
482 aux = accessor _incomingFrom (\fr st -> st { _incomingFrom = fr })
484handleIncomingMessages :: LocalNode -> IO ()
485handleIncomingMessages node = go initConnectionState
486 where
487 go :: ConnectionState -> IO ()
488 go !st = do
489 event <- NT.receive endpoint
490 case event of
491 NT.ConnectionOpened cid rel theirAddr ->
492 if rel == NT.ReliableOrdered
493 then
494 trace node (MxConnected cid theirAddr)
495 >> go (
496 (incomingAt cid ^= Just (theirAddr, Uninit))
497 . (incomingFrom theirAddr ^: Set.insert cid)
498 $ st
499 )
500 else invalidRequest cid st
501 NT.Received cid payload ->
502 case st ^. incomingAt cid of
503 Just (_, ToProc pid weakQueue) -> do
504 mQueue <- deRefWeak weakQueue
505 forM_ mQueue $ \queue -> do
506 -- TODO: if we find that the queue is Nothing, should we remove
507 -- it from the NC state? (and same for channels, below)
508 let msg = payloadToMessage payload
509 enqueue queue msg -- 'enqueue' is strict
510 trace node (MxReceived pid msg)
511 go st
512 Just (_, ToChan (TypedChannel chan')) -> do
513 mChan <- deRefWeak chan'
514 -- If mChan is Nothing, the process has given up the read end of
515 -- the channel and we simply ignore the incoming message
516 forM_ mChan $ \chan -> atomically $
517 -- We make sure the message is fully decoded when it is enqueued
518 writeTQueue chan $! decode (BSL.fromChunks payload)
519 go st
520 Just (_, ToNode) -> do
521 let ctrlMsg = decode . BSL.fromChunks $ payload
522 writeChan ctrlChan $! ctrlMsg
523 go st
524 Just (src, Uninit) ->
525 case decode (BSL.fromChunks payload) of
526 ProcessIdentifier pid -> do
527 let lpid = processLocalId pid
528 mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
529 case mProc of
530 Just proc ->
531 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
532 Nothing ->
533 invalidRequest cid st
534 SendPortIdentifier chId -> do
535 let lcid = sendPortLocalId chId
536 lpid = processLocalId (sendPortProcessId chId)
537 mProc <- withValidLocalState node $ return . (^. localProcessWithId lpid)
538 case mProc of
539 Just proc -> do
540 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
541 case mChannel of
542 Just channel ->
543 go (incomingAt cid ^= Just (src, ToChan channel) $ st)
544 Nothing ->
545 invalidRequest cid st
546 Nothing ->
547 invalidRequest cid st
548 NodeIdentifier nid ->
549 if nid == localNodeId node
550 then go (incomingAt cid ^= Just (src, ToNode) $ st)
551 else invalidRequest cid st
552 Nothing ->
553 invalidRequest cid st
554 NT.ConnectionClosed cid ->
555 case st ^. incomingAt cid of
556 Nothing ->
557 invalidRequest cid st
558 Just (src, _) -> do
559 trace node (MxDisconnected cid src)
560 go ( (incomingAt cid ^= Nothing)
561 . (incomingFrom src ^: Set.delete cid)
562 $ st
563 )
564 NT.ErrorEvent (NT.TransportError (NT.EventConnectionLost theirAddr) _) -> do
565 -- [Unified table 9, rule node_disconnect]
566 let nid = NodeIdentifier $ NodeId theirAddr
567 writeChan ctrlChan NCMsg
568 { ctrlMsgSender = nid
569 , ctrlMsgSignal = Died nid DiedDisconnect
570 }
571 let notLost k = not (k `Set.member` (st ^. incomingFrom theirAddr))
572 closeImplicitReconnections node nid
573 go ( (incomingFrom theirAddr ^= Set.empty)
574 . (incoming ^: Map.filterWithKey (const . notLost))
575 $ st
576 )
577 NT.ErrorEvent (NT.TransportError NT.EventEndPointFailed str) ->
578 fail $ "Cloud Haskell fatal error: end point failed: " ++ str
579 NT.ErrorEvent (NT.TransportError NT.EventTransportFailed str) ->
580 fail $ "Cloud Haskell fatal error: transport failed: " ++ str
581 NT.EndPointClosed ->
582 return ()
583 NT.ReceivedMulticast _ _ ->
584 -- If we received a multicast message, something went horribly wrong
585 -- and we just give up
586 fail "Cloud Haskell fatal error: received unexpected multicast"
588 invalidRequest :: NT.ConnectionId -> ConnectionState -> IO ()
589 invalidRequest cid st = do
590 -- TODO: We should treat this as a fatal error on the part of the remote
591 -- node. That is, we should report the remote node as having died, and we
592 -- should close incoming connections (this requires a Transport layer
593 -- extension).
594 traceEventFmtIO node "" [(TraceStr " [network] invalid request: "),
595 (Trace cid)]
596 go ( incomingAt cid ^= Nothing
597 $ st
598 )
600 endpoint = localEndPoint node
601 ctrlChan = localCtrlChan node
603--------------------------------------------------------------------------------
604-- Top-level access to the node controller --
605--------------------------------------------------------------------------------
607runNodeController :: LocalNode -> IO ()
608runNodeController =
609 runReaderT (evalStateT (unNC nodeController) initNCState)
611--------------------------------------------------------------------------------
612-- Internal data types --
613--------------------------------------------------------------------------------
615data NCState = NCState
616 { -- Mapping from remote processes to linked local processes
617 _links :: !(Map Identifier (Set ProcessId))
618 -- Mapping from remote processes to monitoring local processes
619 , _monitors :: !(Map Identifier (Set (ProcessId, MonitorRef)))
620 -- Process registry: names and where they live, mapped to the PIDs
621 , _registeredHere :: !(Map String ProcessId)
622 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
623 }
625newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
626 deriving ( Applicative
627 , Functor
628 , Monad
629 , MonadIO
630 , MonadState NCState
631 , MonadReader LocalNode
632 )
634initNCState :: NCState
635initNCState = NCState { _links = Map.empty
636 , _monitors = Map.empty
637 , _registeredHere = Map.empty
638 , _registeredOnNodes = Map.empty
639 }
641-- | Thrown in response to the user invoking 'kill' (see Primitives.hs). This
642-- type is deliberately not exported so it cannot be caught explicitly.
643data ProcessKillException =
644 ProcessKillException !ProcessId !String
645 deriving (Typeable)
647instance Exception ProcessKillException
648instance Show ProcessKillException where
649 show (ProcessKillException pid reason) =
650 "killed-by=" ++ show pid ++ ",reason=" ++ reason
652--------------------------------------------------------------------------------
653-- Tracing/Debugging --
654--------------------------------------------------------------------------------
656-- [Issue #104 / DP-13]
658traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
659traceNotifyDied node ident reason =
660 -- TODO: sendPortDied notifications
661 liftIO $ withLocalTracer node $ \t ->
662 case ident of
663 (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
664 (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
665 _ -> return ()
667traceEventFmtIO :: LocalNode
668 -> String
669 -> [TraceArg]
670 -> IO ()
671traceEventFmtIO node fmt args =
672 withLocalTracer node $ \t -> traceLogFmt t fmt args
674trace :: LocalNode -> MxEvent -> IO ()
675trace node ev = withLocalTracer node $ \t -> traceEvent t ev
677withLocalTracer :: LocalNode -> (MxEventBus -> IO ()) -> IO ()
678withLocalTracer node act = act (localEventBus node)
680--------------------------------------------------------------------------------
681-- Core functionality --
682--------------------------------------------------------------------------------
684-- [Unified: Table 7]
685nodeController :: NC ()
686nodeController = do
687 node <- ask
688 forever' $ do
689 msg <- liftIO $ readChan (localCtrlChan node)
691 -- [Unified: Table 7, rule nc_forward]
692 case destNid (ctrlMsgSignal msg) of
693 Just nid' | nid' /= localNodeId node ->
694 liftIO $ sendBinary node
695 (ctrlMsgSender msg)
696 (NodeIdentifier nid')
697 WithImplicitReconnect
698 msg
699 _ ->
700 return ()
702 case msg of
703 NCMsg (ProcessIdentifier from) (Link them) ->
704 ncEffectMonitor from them Nothing
705 NCMsg (ProcessIdentifier from) (Monitor ref) ->
706 ncEffectMonitor from (monitorRefIdent ref) (Just ref)
707 NCMsg (ProcessIdentifier from) (Unlink them) ->
708 ncEffectUnlink from them
709 NCMsg (ProcessIdentifier from) (Unmonitor ref) ->
710 ncEffectUnmonitor from ref
711 NCMsg _from (Died ident reason) ->
712 ncEffectDied ident reason
713 NCMsg (ProcessIdentifier from) (Spawn proc ref) ->
714 ncEffectSpawn from proc ref
715 NCMsg (ProcessIdentifier from) (Register label atnode pid force) ->
716 ncEffectRegister from label atnode pid force
717 NCMsg (ProcessIdentifier from) (WhereIs label) ->
718 ncEffectWhereIs from label
719 NCMsg (ProcessIdentifier from) (NamedSend label msg') ->
720 ncEffectNamedSend from label msg'
721 NCMsg _ (UnreliableSend lpid msg') ->
722 ncEffectLocalSend node (ProcessId (localNodeId node) lpid) msg'
723 NCMsg _ (LocalSend to msg') ->
724 ncEffectLocalSend node to msg'
725 NCMsg _ (LocalPortSend to msg') ->
726 ncEffectLocalPortSend to msg'
727 NCMsg (ProcessIdentifier from) (Kill to reason) ->
728 ncEffectKill from to reason
729 NCMsg (ProcessIdentifier from) (Exit to reason) ->
730 ncEffectExit from to reason
731 NCMsg (ProcessIdentifier from) (GetInfo pid) ->
732 ncEffectGetInfo from pid
733 NCMsg _ SigShutdown ->
734 liftIO $ do
735 NT.closeEndPoint (localEndPoint node)
736 `Exception.finally` throwIO ThreadKilled
737 -- ThreadKilled seems to make more sense than fail/error here
738 NCMsg (ProcessIdentifier from) (GetNodeStats nid) ->
739 ncEffectGetNodeStats from nid
740 unexpected ->
741 error $ "nodeController: unexpected message " ++ show unexpected
743-- [Unified: Table 10]
744ncEffectMonitor :: ProcessId -- ^ Who's watching?
745 -> Identifier -- ^ Who's being watched?
746 -> Maybe MonitorRef -- ^ 'Nothing' to link
747 -> NC ()
748ncEffectMonitor from them mRef = do
749 node <- ask
750 shouldLink <-
751 if not (isLocal node them)
752 then return True
753 else isValidLocalIdentifier them
754 case (shouldLink, isLocal node (ProcessIdentifier from)) of
755 (True, _) -> -- [Unified: first rule]
756 case mRef of
757 Just ref -> modify' $ monitorsFor them ^: Set.insert (from, ref)
758 Nothing -> modify' $ linksFor them ^: Set.insert from
759 (False, True) -> -- [Unified: second rule]
760 notifyDied from them DiedUnknownId mRef
761 (False, False) -> -- [Unified: third rule]
762 -- TODO: this is the right sender according to the Unified semantics,
763 -- but perhaps having 'them' as the sender would make more sense
764 -- (see also: notifyDied)
765 liftIO $ sendBinary node
766 (NodeIdentifier $ localNodeId node)
767 (NodeIdentifier $ processNodeId from)
768 WithImplicitReconnect
769 NCMsg
770 { ctrlMsgSender = NodeIdentifier (localNodeId node)
771 , ctrlMsgSignal = Died them DiedUnknownId
772 }
774-- [Unified: Table 11]
775ncEffectUnlink :: ProcessId -> Identifier -> NC ()
776ncEffectUnlink from them = do
777 node <- ask
778 when (isLocal node (ProcessIdentifier from)) $
779 case them of
780 ProcessIdentifier pid ->
781 postAsMessage from $ DidUnlinkProcess pid
782 NodeIdentifier nid ->
783 postAsMessage from $ DidUnlinkNode nid
784 SendPortIdentifier cid ->
785 postAsMessage from $ DidUnlinkPort cid
786 modify' $ linksFor them ^: Set.delete from
788-- [Unified: Table 11]
789ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
790ncEffectUnmonitor from ref = do
791 node <- ask
792 when (isLocal node (ProcessIdentifier from)) $
793 postAsMessage from $ DidUnmonitor ref
794 modify' $ monitorsFor (monitorRefIdent ref) ^: Set.delete (from, ref)
796-- [Unified: Table 12]
797ncEffectDied :: Identifier -> DiedReason -> NC ()
798ncEffectDied ident reason = do
799 node <- ask
800 traceNotifyDied node ident reason
801 (affectedLinks, unaffectedLinks) <- gets (splitNotif ident . (^. links))
802 (affectedMons, unaffectedMons) <- gets (splitNotif ident . (^. monitors))
804-- _registry :: !(Map (String,NodeId) ProcessId)
806 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
808 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
809 forM_ uss $ \us ->
810 when (localOnly <= isLocal node (ProcessIdentifier us)) $
811 notifyDied us them reason Nothing
813 forM_ (Map.toList affectedMons) $ \(them, refs) ->
814 forM_ refs $ \(us, ref) ->
815 when (localOnly <= isLocal node (ProcessIdentifier us)) $
816 notifyDied us them reason (Just ref)
818 modify' $ (links ^= unaffectedLinks) . (monitors ^= unaffectedMons)
820 modify' $ registeredHere ^: Map.filter (\pid -> not $ ident `impliesDeathOf` ProcessIdentifier pid)
822 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
823 mapM (\(pid,nidlist) ->
824 case ident `impliesDeathOf` ProcessIdentifier pid of
825 True ->
826 do forM_ nidlist $ \(nid,_) ->
827 when (not $ isLocal node (NodeIdentifier nid))
828 (forwardNameDeath node nid)
829 return Nothing
830 False -> return $ Just (pid,nidlist) )
831 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
832 where
833 forwardNameDeath node nid =
834 liftIO $ sendBinary node
835 (NodeIdentifier $ localNodeId node)
836 (NodeIdentifier $ nid)
837 WithImplicitReconnect
838 NCMsg
839 { ctrlMsgSender = NodeIdentifier (localNodeId node)
840 , ctrlMsgSignal = Died ident reason
841 }
843-- [Unified: Table 13]
844ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
845ncEffectSpawn pid cProc ref = do
846 mProc <- unClosure cProc
847 -- If the closure does not exist, we spawn a process that throws an exception
848 -- This allows the remote node to find out what's happening
849 -- TODO:
850 let proc = case mProc of
851 Left err -> fail $ "Error: Could not resolve closure: " ++ err
852 Right p -> p
853 node <- ask
854 pid' <- liftIO $ forkProcess node proc
855 liftIO $ sendMessage node
856 (NodeIdentifier (localNodeId node))
857 (ProcessIdentifier pid)
858 WithImplicitReconnect
859 (DidSpawn ref pid')
861-- Unified semantics does not explicitly describe how to implement 'register',
862-- but mentions it's "very similar to nsend" (Table 14)
863-- We send a response indicated if the operation is invalid
864ncEffectRegister :: ProcessId -> String -> NodeId -> Maybe ProcessId -> Bool -> NC ()
865ncEffectRegister from label atnode mPid reregistration = do
866 node <- ask
867 currentVal <- gets (^. registeredHereFor label)
868 isOk <-
869 case mPid of
870 Nothing -> -- unregister request
871 return $ isJust currentVal
872 Just thepid -> -- register request
873 do isvalidlocal <- isValidLocalIdentifier (ProcessIdentifier thepid)
874 return $ (isNothing currentVal /= reregistration) &&
875 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
876 if isLocal node (NodeIdentifier atnode)
877 then do when isOk $
878 do modify' $ registeredHereFor label ^= mPid
879 updateRemote node currentVal mPid
880 case mPid of
881 (Just p) -> liftIO $ trace node (MxRegistered p label)
882 Nothing -> liftIO $ trace node (MxUnRegistered (fromJust currentVal) label)
883 newVal <- gets (^. registeredHereFor label)
884 liftIO $ sendMessage node
885 (NodeIdentifier (localNodeId node))
886 (ProcessIdentifier from)
887 WithImplicitReconnect
888 (RegisterReply label isOk newVal)
889 else let operation =
890 case reregistration of
891 True -> flip decList
892 False -> flip incList
893 in case mPid of
894 Nothing -> return ()
895 Just pid -> modify' $ registeredOnNodesFor pid ^: (maybeify $ operation atnode)
896 where updateRemote node (Just oldval) (Just newval) | processNodeId oldval /= processNodeId newval =
897 do forward node (processNodeId oldval) (Register label atnode (Just oldval) True)
898 forward node (processNodeId newval) (Register label atnode (Just newval) False)
899 updateRemote node Nothing (Just newval) =
900 forward node (processNodeId newval) (Register label atnode (Just newval) False)
901 updateRemote node (Just oldval) Nothing =
902 forward node (processNodeId oldval) (Register label atnode (Just oldval) True)
903 updateRemote _ _ _ = return ()
904 maybeify f Nothing = unmaybeify $ f []
905 maybeify f (Just x) = unmaybeify $ f x
907 unmaybeify [] = Nothing
908 unmaybeify x = Just x
909 incList [] tag = [(tag,1)]
910 incList ((atag,acount):xs) tag | tag==atag = (atag,acount+1) : xs
911 incList (x:xs) tag = x : incList xs tag
912 decList [] _ = []
913 decList ((atag,1):xs) tag | atag == tag = xs
914 decList ((atag,n):xs) tag | atag == tag = (atag,n-1):xs
915 decList (x:xs) tag = x:decList xs tag
916 forward node to reg =
917 when (not $ isLocal node (NodeIdentifier to)) $
918 liftIO $ sendBinary node
919 (ProcessIdentifier from)
920 (NodeIdentifier to)
921 WithImplicitReconnect
922 NCMsg
923 { ctrlMsgSender = ProcessIdentifier from
924 , ctrlMsgSignal = reg
925 }
928-- Unified semantics does not explicitly describe 'whereis'
929ncEffectWhereIs :: ProcessId -> String -> NC ()
930ncEffectWhereIs from label = do
931 node <- ask
932 mPid <- gets (^. registeredHereFor label)
933 liftIO $ sendMessage node
934 (NodeIdentifier (localNodeId node))
935 (ProcessIdentifier from)
936 WithImplicitReconnect
937 (WhereIsReply label mPid)
939-- [Unified: Table 14]
940ncEffectNamedSend :: ProcessId -> String -> Message -> NC ()
941ncEffectNamedSend from label msg = do
942 mPid <- gets (^. registeredHereFor label)
943 node <- ask
944 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
945 forM_ mPid $ \pid ->
946 liftIO $ sendPayload node
947 (ProcessIdentifier from)
948 (ProcessIdentifier pid)
949 NoImplicitReconnect
950 (messageToPayload msg)
952-- [Issue #DP-20]
953ncEffectLocalSend :: LocalNode -> ProcessId -> Message -> NC ()
954ncEffectLocalSend node to msg =
955 liftIO $ withLocalProc node to $ \p -> do
956 enqueue (processQueue p) msg
957 trace node (MxReceived to msg)
959-- [Issue #DP-20]
960ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
961ncEffectLocalPortSend from msg = do
962 node <- ask
963 let pid = sendPortProcessId from
964 cid = sendPortLocalId from
965 liftIO $ withLocalProc node pid $ \proc -> do
966 mChan <- withMVar (processState proc) $ return . (^. typedChannelWithId cid)
967 case mChan of
968 -- in the unlikely event we know nothing about this channel id,
969 -- there's little to be done - perhaps some logging/tracing though...
970 Nothing -> return ()
971 Just (TypedChannel chan') -> do
972 -- If ch is Nothing, the process has given up the read end of
973 -- the channel and we simply ignore the incoming message - this
974 ch <- deRefWeak chan'
975 forM_ ch $ \chan -> deliverChan msg chan
976 where deliverChan :: forall a . Message -> TQueue a -> IO ()
977 deliverChan (UnencodedMessage _ raw) chan' =
978 atomically $ writeTQueue chan' ((unsafeCoerce raw) :: a)
979 deliverChan (EncodedMessage _ _) _ =
980 -- this will not happen unless someone screws with Primitives.hs
981 error "invalid local channel delivery"
983-- [Issue #69]
984ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
985ncEffectKill from to reason = do
986 node <- ask
987 when (isLocal node (ProcessIdentifier to)) $
988 throwException to $ ProcessKillException from reason
990-- [Issue #69]
991ncEffectExit :: ProcessId -> ProcessId -> Message -> NC ()
992ncEffectExit from to reason = do
993 node <- ask
994 when (isLocal node (ProcessIdentifier to)) $
995 throwException to $ ProcessExitException from reason
997-- [Issue #89]
998ncEffectGetInfo :: ProcessId -> ProcessId -> NC ()
999ncEffectGetInfo from pid =
1000 let lpid = processLocalId pid
1001 them = (ProcessIdentifier pid)
1002 in do
1003 node <- ask
1004 mProc <- liftIO $ withValidLocalState node
1005 $ return . (^. localProcessWithId lpid)
1006 case mProc of
1007 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
1008 from node (ProcessInfoNone DiedUnknownId)
1009 Just proc -> do
1010 itsLinks <- gets (^. linksFor them)
1011 itsMons <- gets (^. monitorsFor them)
1012 registered <- gets (^. registeredHere)
1013 size <- liftIO $ queueSize $ processQueue $ proc
1015 let reg = registeredNames registered
1016 dispatch (isLocal node (ProcessIdentifier from))
1017 from
1018 node
1019 ProcessInfo {
1020 infoNode = (processNodeId pid)
1021 , infoRegisteredNames = reg
1022 , infoMessageQueueLength = size
1023 , infoMonitors = Set.toList itsMons
1024 , infoLinks = Set.toList itsLinks
1026 where dispatch :: (Serializable a, Show a)
1027 => Bool
1028 -> ProcessId
1029 -> LocalNode
1030 -> a
1031 -> NC ()
1032 dispatch True dest _ pInfo = postAsMessage dest $ pInfo
1033 dispatch False dest node pInfo = do
1034 liftIO $ sendMessage node
1035 (NodeIdentifier (localNodeId node))
1036 (ProcessIdentifier dest)
1037 WithImplicitReconnect
1038 pInfo
1040 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
1041 then (k:ks)
1042 else ks) []
1044ncEffectGetNodeStats :: ProcessId -> NodeId -> NC ()
1045ncEffectGetNodeStats from _nid = do
1046 node <- ask
1047 ncState <- StateT.get
1048 nodeState <- liftIO $ withValidLocalState node return
1049 let stats =
1050 NodeStats {
1051 nodeStatsNode = localNodeId node
1052 , nodeStatsRegisteredNames = Map.size $ ncState ^. registeredHere
1053 , nodeStatsMonitors = Map.size $ ncState ^. monitors
1054 , nodeStatsLinks = Map.size $ ncState ^. links
1055 , nodeStatsProcesses = Map.size (nodeState ^. localProcesses)
1057 postAsMessage from stats
1059--------------------------------------------------------------------------------
1060-- Auxiliary --
1061--------------------------------------------------------------------------------
1063notifyDied :: ProcessId -- ^ Who to notify?
1064 -> Identifier -- ^ Who died?
1065 -> DiedReason -- ^ How did they die?
1066 -> Maybe MonitorRef -- ^ 'Nothing' for linking
1067 -> NC ()
1068notifyDied dest src reason mRef = do
1069 node <- ask
1070 case (isLocal node (ProcessIdentifier dest), mRef, src) of
1071 (True, Just ref, ProcessIdentifier pid) ->
1072 postAsMessage dest $ ProcessMonitorNotification ref pid reason
1073 (True, Just ref, NodeIdentifier nid) ->
1074 postAsMessage dest $ NodeMonitorNotification ref nid reason
1075 (True, Just ref, SendPortIdentifier cid) ->
1076 postAsMessage dest $ PortMonitorNotification ref cid reason
1077 (True, Nothing, ProcessIdentifier pid) ->
1078 throwException dest $ ProcessLinkException pid reason
1079 (True, Nothing, NodeIdentifier pid) ->
1080 throwException dest $ NodeLinkException pid reason
1081 (True, Nothing, SendPortIdentifier pid) ->
1082 throwException dest $ PortLinkException pid reason
1083 (False, _, _) ->
1084 -- The change in sender comes from [Unified: Table 10]
1085 liftIO $ sendBinary node
1086 (NodeIdentifier $ localNodeId node)
1087 (NodeIdentifier $ processNodeId dest)
1088 WithImplicitReconnect
1089 NCMsg
1090 { ctrlMsgSender = NodeIdentifier (localNodeId node)
1091 , ctrlMsgSignal = Died src reason
1094-- | [Unified: Table 8]
1095destNid :: ProcessSignal -> Maybe NodeId
1096destNid (Link ident) = Just $ nodeOf ident
1097destNid (Unlink ident) = Just $ nodeOf ident
1098destNid (Monitor ref) = Just $ nodeOf (monitorRefIdent ref)
1099destNid (Unmonitor ref) = Just $ nodeOf (monitorRefIdent ref)
1100destNid (Spawn _ _) = Nothing
1101destNid (Register _ _ _ _) = Nothing
1102destNid (WhereIs _) = Nothing
1103destNid (NamedSend _ _) = Nothing
1104destNid (UnreliableSend _ _) = Nothing
1105-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
1106-- then when a local process dies the monitoring/linking machinery will take
1107-- care of notifying remote nodes
1108destNid (Died _ _) = Nothing
1109destNid (Kill pid _) = Just $ processNodeId pid
1110destNid (Exit pid _) = Just $ processNodeId pid
1111destNid (GetInfo pid) = Just $ processNodeId pid
1112destNid (GetNodeStats nid) = Just nid
1113destNid (LocalSend pid _) = Just $ processNodeId pid
1114destNid (LocalPortSend cid _) = Just $ processNodeId (sendPortProcessId cid)
1115destNid (SigShutdown) = Nothing
1117-- | Check if a process is local to our own node
1118isLocal :: LocalNode -> Identifier -> Bool
1119isLocal nid ident = nodeOf ident == localNodeId nid
1121-- | Lookup a local closure
1122unClosure :: Typeable a => Closure a -> NC (Either String a)
1123unClosure closure = do
1124 rtable <- remoteTable <$> ask
1125 return (Static.unclosure rtable closure)
1127-- | Check if an identifier refers to a valid local object
1128isValidLocalIdentifier :: Identifier -> NC Bool
1129isValidLocalIdentifier ident = do
1130 node <- ask
1131 liftIO . withValidLocalState node $ \nSt ->
1132 case ident of
1133 NodeIdentifier nid ->
1134 return $ nid == localNodeId node
1135 ProcessIdentifier pid -> do
1136 let mProc = nSt ^. localProcessWithId (processLocalId pid)
1137 return $ isJust mProc
1138 SendPortIdentifier cid -> do
1139 let pid = sendPortProcessId cid
1140 mProc = nSt ^. localProcessWithId (processLocalId pid)
1141 case mProc of
1142 Nothing -> return False
1143 Just proc -> withMVar (processState proc) $ \pSt -> do
1144 let mCh = pSt ^. typedChannelWithId (sendPortLocalId cid)
1145 return $ isJust mCh
1147--------------------------------------------------------------------------------
1148-- Messages to local processes --
1149--------------------------------------------------------------------------------
1151postAsMessage :: Serializable a => ProcessId -> a -> NC ()
1152postAsMessage pid = postMessage pid . createUnencodedMessage
1154postMessage :: ProcessId -> Message -> NC ()
1155postMessage pid msg = do
1156 node <- ask
1157 liftIO $ withLocalProc node pid $ \p -> enqueue (processQueue p) msg
1159throwException :: Exception e => ProcessId -> e -> NC ()
1160throwException pid e = do
1161 node <- ask
1162 -- throwTo blocks until the exception is received by the target thread.
1163 -- We fork a helper thread to avoid blocking the node controller.
1164 liftIO $ withLocalProc node pid $ \p -> void $ forkIO $ throwTo (processThread p) e
1166withLocalProc :: LocalNode -> ProcessId -> (LocalProcess -> IO ()) -> IO ()
1167withLocalProc node pid p =
1168 -- By [Unified: table 6, rule missing_process] messages to dead processes
1169 -- can silently be dropped
1170 let lpid = processLocalId pid in do
1171 withValidLocalState node $ \vst ->
1172 forM_ (vst ^. localProcessWithId lpid) p
1174--------------------------------------------------------------------------------
1175-- Accessors --
1176--------------------------------------------------------------------------------
1178links :: Accessor NCState (Map Identifier (Set ProcessId))
1179links = accessor _links (\ls st -> st { _links = ls })
1181monitors :: Accessor NCState (Map Identifier (Set (ProcessId, MonitorRef)))
1182monitors = accessor _monitors (\ms st -> st { _monitors = ms })
1184registeredHere :: Accessor NCState (Map String ProcessId)
1185registeredHere = accessor _registeredHere (\ry st -> st { _registeredHere = ry })
1187registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
1188registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
1190linksFor :: Identifier -> Accessor NCState (Set ProcessId)
1191linksFor ident = links >>> DAC.mapDefault Set.empty ident
1193monitorsFor :: Identifier -> Accessor NCState (Set (ProcessId, MonitorRef))
1194monitorsFor ident = monitors >>> DAC.mapDefault Set.empty ident
1196registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
1197registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
1199registeredOnNodesFor :: ProcessId -> Accessor NCState (Maybe [(NodeId,Int)])
1200registeredOnNodesFor ident = registeredOnNodes >>> DAC.mapMaybe ident
1202-- | @splitNotif ident@ splits a notifications map into those
1203-- notifications that should trigger when 'ident' fails and those links that
1204-- should not.
1206-- There is a hierarchy between identifiers: failure of a node implies failure
1207-- of all processes on that node, and failure of a process implies failure of
1208-- all typed channels to that process. In other words, if 'ident' refers to a
1209-- node, then the /should trigger/ set will include
1211-- * the notifications for the node specifically
1212-- * the notifications for processes on that node, and
1213-- * the notifications for typed channels to processes on that node.
1215-- Similarly, if 'ident' refers to a process, the /should trigger/ set will
1216-- include
1218-- * the notifications for that process specifically and
1219-- * the notifications for typed channels to that process.
1221-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1222splitNotif :: Identifier
1223 -> Map Identifier a
1224 -> (Map Identifier a, Map Identifier a)
1225splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1227--------------------------------------------------------------------------------
1228-- Auxiliary --
1229--------------------------------------------------------------------------------
1231-- | Modify and evaluate the state
1232modify' :: MonadState s m => (s -> s) -> m ()
1233modify' f = StateT.get >>= \s -> StateT.put $! f s