2{-# LANGUAGE DeriveDataTypeable #-}
3{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE RankNTypes #-}
5{-# LANGUAGE BangPatterns #-}
6{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7{-# LANGUAGE RecordWildCards #-}
11module Control.Distributed.Process.Node
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)
27import System.IO (fixIO, hPutStrLn, stderr)
28import System.Mem.Weak (Weak, deRefWeak)
29import qualified Data.ByteString.Lazy as BSL (fromChunks)
30import Data.Binary (decode)
32import qualified Data.Map as Map
44import qualified Data.Set as Set
51import Data.Foldable (forM_)
52import Data.Maybe (isJust, fromJust, isNothing, catMaybes)
53import Data.Typeable (Typeable)
54import Control.Category ((>>>))
55import Control.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
63 , AsyncException(ThreadKilled)
68import qualified Control.Exception as Exception (Handler(..), catches, finally)
69import Control.Concurrent (forkIO, myThreadId)
70import Control.Distributed.Process.Internal.StrictMVar
80import Control.Concurrent.Chan (newChan, writeChan, readChan)
81import qualified Control.Concurrent.MVar as MVar (newEmptyMVar, takeMVar)
82import Control.Concurrent.STM
85import Control.Distributed.Process.Internal.CQueue
91import qualified Network.Transport as NT
105 , Reliability(ReliableOrdered)
107import Data.Accessor (Accessor, accessor, (^.), (^=), (^:))
108import System.Random (randomIO)
109import Control.Distributed.Static (RemoteTable, Closure)
110import qualified Control.Distributed.Static as Static
114import Control.Distributed.Process.Internal.Types
122 , LocalProcessState(..)
134 , ProcessMonitorNotification(..)
135 , NodeMonitorNotification(..)
136 , PortMonitorNotification(..)
137 , ProcessExitException(..)
138 , ProcessLinkException(..)
139 , NodeLinkException(..)
140 , PortLinkException(..)
142 , DidUnlinkProcess(..)
152 , ProcessInfoNone(..)
159 , createUnencodedMessage
161 , firstNonReservedProcessId
162 , ImplicitReconnect(WithImplicitReconnect)
164import Control.Distributed.Process.Management.Internal.Agent
167import qualified Control.Distributed.Process.Management.Internal.Table as Table
169 , startTableCoordinator
171import qualified Control.Distributed.Process.Management.Internal.Trace.Remote as Trace
174import Control.Distributed.Process.Management.Internal.Trace.Tracer
177import Control.Distributed.Process.Management.Internal.Trace.Types
183import Control.Distributed.Process.Management.Internal.Types
186import Control.Distributed.Process.Serializable (Serializable)
187import Control.Distributed.Process.Internal.Messaging
190 , closeImplicitReconnections
193import Control.Distributed.Process.Internal.Primitives
202import Control.Distributed.Process.Internal.Types (SendPort, Tracer(..))
203import qualified Control.Distributed.Process.Internal.Closure.BuiltIn as BuiltIn (remoteTable)
204import Control.Distributed.Process.Internal.WeakTQueue (TQueue, writeTQueue)
205import qualified Control.Distributed.Process.Internal.StrictContainerAccessors as DAC
211--------------------------------------------------------------------------------
213--------------------------------------------------------------------------------
215initRemoteTable :: RemoteTable
216initRemoteTable = Trace.remoteTable $ BuiltIn.remoteTable Static.initRemoteTable
218-- | Initialize a new local node.
219newLocalNode :: NT.Transport -> RemoteTable -> IO LocalNode
220newLocalNode transport rtable = do
221 mEndPoint <- NT.newEndPoint transport
223 Left ex -> throwIO ex
225 localNode <- createBareLocalNode endPoint rtable
226 startServiceProcesses localNode
229-- | Create a new local node (without any service processes running)
230createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
231createBareLocalNode endPoint rtable = do
233 state <- newMVar LocalNodeState
234 { _localProcesses = Map.empty
235 , _localPidCounter = firstNonReservedProcessId
236 , _localPidUnique = unq
237 , _localConnections = Map.empty
240 let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
241 , localEndPoint = endPoint
243 , localCtrlChan = ctrlChan
244 , localEventBus = MxEventBusInitialising
245 , remoteTable = rtable
247 tracedNode <- startMxAgent node
249 -- Once the NC terminates, the endpoint isn't much use,
250 void $ forkIO $ Exception.finally (runNodeController tracedNode)
251 (NT.closeEndPoint (localEndPoint node))
253 -- whilst a closed/failing endpoint will terminate the NC
254 void $ forkIO $ Exception.finally (handleIncomingMessages tracedNode)
260 writeChan (localCtrlChan node) NCMsg
261 { ctrlMsgSender = NodeIdentifier (localNodeId node)
262 , ctrlMsgSignal = SigShutdown
265startMxAgent :: LocalNode -> IO LocalNode
266startMxAgent node = do
267 -- see note [tracer/forkProcess races]
268 let fork = forkProcess node
269 mv <- MVar.newEmptyMVar
270 pid <- fork $ mxAgentController fork mv
271 (tracer', wqRef, mxNew') <- MVar.takeMVar mv
272 return node { localEventBus = (MxEventBus pid tracer' wqRef mxNew') }
274startDefaultTracer :: LocalNode -> IO ()
275startDefaultTracer node' = do
276 let t = localEventBus node'
278 MxEventBus _ (Tracer pid _) _ _ -> do
279 runProcess node' $ register "trace.controller" pid
280 pid' <- forkProcess node' defaultTracer
281 enableTrace (localEventBus node') pid'
282 runProcess node' $ register "tracer.initial" pid'
285-- TODO: we need a better mechanism for defining and registering services
287-- | Start and register the service processes on a node
288startServiceProcesses :: LocalNode -> IO ()
289startServiceProcesses node = do
290 -- tracing /spawns/ relies on the tracer being enabled, but we start
291 -- the default tracer first, even though it might @nsend@ to the logger
292 -- before /that/ process has started - this is a totally harmless race
293 -- however, so we deliberably ignore it
294 startDefaultTracer node
295 tableCoordinatorPid <- fork $ Table.startTableCoordinator fork
296 runProcess node $ register Table.mxTableCoordinator tableCoordinatorPid
297 logger <- forkProcess node loop
298 runProcess node $ register "logger" logger
300 fork = forkProcess node
304 [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
305 liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
307 , match $ \((time, string) :: (String, String)) -> do
308 -- this is a 'trace' message from the local node tracer
309 liftIO . hPutStrLn stderr $ time ++ " [trace] " ++ string
311 , match $ \(ch :: SendPort ()) -> -- a shutdown request
315-- | Force-close a local node
317-- TODO: for now we just close the associated endpoint
318closeLocalNode :: LocalNode -> IO ()
320 -- TODO: close all our processes, surely!?
321 NT.closeEndPoint (localEndPoint node)
323-- | Run a process on a local node and wait for it to finish
324runProcess :: LocalNode -> Process () -> IO ()
325runProcess node proc = do
328 void $ forkProcess node $ do
329 catch (proc `finally` liftIO (putMVar done ()))
330 (\(ex :: SomeException) -> liftIO $ throwTo tid ex)
333-- | Spawn a new process on a local node
334forkProcess :: LocalNode -> Process () -> IO ProcessId
335forkProcess node proc = modifyMVar (localState node) startProcess
337 startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
339 let lpid = LocalProcessId { lpidCounter = st ^. localPidCounter
340 , lpidUnique = st ^. localPidUnique
342 let pid = ProcessId { processNodeId = localNodeId node
343 , processLocalId = lpid
345 pst <- newMVar LocalProcessState { _monitorCounter = 0
347 , _channelCounter = 0
348 , _typedChannels = Map.empty
351 weakQueue <- mkWeakCQueue queue (return ())
352 (_, lproc) <- fixIO $ \ ~(tid, _) -> do
353 let lproc = LocalProcess { processQueue = queue
354 , processWeakQ = weakQueue
357 , processThread = tid
361 reason <- Exception.catches
362 (runLocalProcess lproc proc >> return DiedNormal)
363 [ (Exception.Handler (\ex@(ProcessExitException from msg) -> do
364 mMsg <- unwrapMessage msg :: IO (Maybe String)
366 Nothing -> return $ DiedException $ show ex
367 Just m -> return $ DiedException ("exit-from=" ++ (show from) ++ ",reason=" ++ m)))
369 (return . DiedException . (show :: SomeException -> String)))]
371 -- [Unified: Table 4, rules termination and exiting]
372 modifyMVar_ (localState node) (cleanupProcess pid)
373 writeChan (localCtrlChan node) NCMsg
374 { ctrlMsgSender = ProcessIdentifier pid
375 , ctrlMsgSignal = Died (ProcessIdentifier pid) reason
379 -- see note [tracer/forkProcess races]
380 trace node (MxSpawned pid)
382 if lpidCounter lpid == maxBound
384 -- TODO: this doesn't look right at all - how do we know
385 -- that newUnique represents a process id that is available!?
386 newUnique <- randomIO
387 return ( (localProcessWithId lpid ^= Just lproc)
388 . (localPidCounter ^= firstNonReservedProcessId)
389 . (localPidUnique ^= newUnique)
394 return ( (localProcessWithId lpid ^= Just lproc)
395 . (localPidCounter ^: (+ 1))
400 cleanupProcess :: ProcessId -> LocalNodeState -> IO LocalNodeState
401 cleanupProcess pid st = do
402 let pid' = ProcessIdentifier pid
403 let (affected, unaffected) = Map.partitionWithKey (\(fr, _to) !_v -> impliesDeathOf pid' fr) (st ^. localConnections)
404 mapM_ (NT.close . fst) (Map.elems affected)
405 return $ (localProcessWithId (processLocalId pid) ^= Nothing)
406 . (localConnections ^= unaffected)
409-- note [tracer/forkProcess races]
411-- Our startTracing function uses forkProcess to start the trace controller
412-- process, and of course forkProcess attempts to call traceEvent once the
413-- process has started. This is harmless, as the localEventBus is not updated
414-- until /after/ the initial forkProcess completes, so the first call to
415-- traceEvent behaves as if tracing were disabled (i.e., it is ignored).
418--------------------------------------------------------------------------------
419-- Handle incoming messages --
420--------------------------------------------------------------------------------
422type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
426 | ToProc ProcessId (Weak (CQueue Message))
427 | ToChan TypedChannel
430data ConnectionState = ConnectionState {
431 _incoming :: !(Map NT.ConnectionId IncomingConnection)
432 , _incomingFrom :: !(Map NT.EndPointAddress (Set NT.ConnectionId))
435initConnectionState :: ConnectionState
436initConnectionState = ConnectionState {
437 _incoming = Map.empty
438 , _incomingFrom = Map.empty
441incoming :: Accessor ConnectionState (Map NT.ConnectionId IncomingConnection)
442incoming = accessor _incoming (\conns st -> st { _incoming = conns })
444incomingAt :: NT.ConnectionId -> Accessor ConnectionState (Maybe IncomingConnection)
445incomingAt cid = incoming >>> DAC.mapMaybe cid
447incomingFrom :: NT.EndPointAddress -> Accessor ConnectionState (Set NT.ConnectionId)
448incomingFrom addr = aux >>> DAC.mapDefault Set.empty addr
450 aux = accessor _incomingFrom (\fr st -> st { _incomingFrom = fr })
452handleIncomingMessages :: LocalNode -> IO ()
453handleIncomingMessages node = go initConnectionState
455 go :: ConnectionState -> IO ()
457 event <- NT.receive endpoint
459 NT.ConnectionOpened cid rel theirAddr ->
460 if rel == NT.ReliableOrdered
462 trace node (MxConnected cid theirAddr)
464 (incomingAt cid ^= Just (theirAddr, Uninit))
465 . (incomingFrom theirAddr ^: Set.insert cid)
468 else invalidRequest cid st
469 NT.Received cid payload ->
470 case st ^. incomingAt cid of
471 Just (_, ToProc pid weakQueue) -> do
472 mQueue <- deRefWeak weakQueue
473 forM_ mQueue $ \queue -> do
474 -- TODO: if we find that the queue is Nothing, should we remove
475 -- it from the NC state? (and same for channels, below)
476 let msg = payloadToMessage payload
477 enqueue queue msg -- 'enqueue' is strict
478 trace node (MxReceived pid msg)
480 Just (_, ToChan (TypedChannel chan')) -> do
481 mChan <- deRefWeak chan'
482 -- If mChan is Nothing, the process has given up the read end of
483 -- the channel and we simply ignore the incoming message
484 forM_ mChan $ \chan -> atomically $
485 -- We make sure the message is fully decoded when it is enqueued
486 writeTQueue chan $! decode (BSL.fromChunks payload)
488 Just (_, ToNode) -> do
489 let ctrlMsg = decode . BSL.fromChunks $ payload
490 writeChan ctrlChan $! ctrlMsg
492 Just (src, Uninit) ->
493 case decode (BSL.fromChunks payload) of
494 ProcessIdentifier pid -> do
495 let lpid = processLocalId pid
496 mProc <- withMVar state $ return . (^. localProcessWithId lpid)
499 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
501 invalidRequest cid st
502 SendPortIdentifier chId -> do
503 let lcid = sendPortLocalId chId
504 lpid = processLocalId (sendPortProcessId chId)
505 mProc <- withMVar state $ return . (^. localProcessWithId lpid)
508 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
511 go (incomingAt cid ^= Just (src, ToChan channel) $ st)
513 invalidRequest cid st
515 invalidRequest cid st
516 NodeIdentifier nid ->
517 if nid == localNodeId node
518 then go (incomingAt cid ^= Just (src, ToNode) $ st)
519 else invalidRequest cid st
521 invalidRequest cid st
522 NT.ConnectionClosed cid ->
523 case st ^. incomingAt cid of
525 invalidRequest cid st
527 trace node (MxDisconnected cid src)
528 go ( (incomingAt cid ^= Nothing)
529 . (incomingFrom src ^: Set.delete cid)
532 NT.ErrorEvent (NT.TransportError (NT.EventConnectionLost theirAddr) _) -> do
533 -- [Unified table 9, rule node_disconnect]
534 let nid = NodeIdentifier $ NodeId theirAddr
535 writeChan ctrlChan NCMsg
536 { ctrlMsgSender = nid
537 , ctrlMsgSignal = Died nid DiedDisconnect
539 let notLost k = not (k `Set.member` (st ^. incomingFrom theirAddr))
540 closeImplicitReconnections node nid
541 go ( (incomingFrom theirAddr ^= Set.empty)
542 . (incoming ^: Map.filterWithKey (const . notLost))
545 NT.ErrorEvent (NT.TransportError NT.EventEndPointFailed str) ->
546 fail $ "Cloud Haskell fatal error: end point failed: " ++ str
547 NT.ErrorEvent (NT.TransportError NT.EventTransportFailed str) ->
548 fail $ "Cloud Haskell fatal error: transport failed: " ++ str
551 NT.ReceivedMulticast _ _ ->
552 -- If we received a multicast message, something went horribly wrong
553 -- and we just give up
554 fail "Cloud Haskell fatal error: received unexpected multicast"
556 invalidRequest :: NT.ConnectionId -> ConnectionState -> IO ()
557 invalidRequest cid st = do
558 -- TODO: We should treat this as a fatal error on the part of the remote
559 -- node. That is, we should report the remote node as having died, and we
560 -- should close incoming connections (this requires a Transport layer
562 traceEventFmtIO node "" [(TraceStr " [network] invalid request: "),
564 go ( incomingAt cid ^= Nothing
568 state = localState node
569 endpoint = localEndPoint node
570 ctrlChan = localCtrlChan node
572--------------------------------------------------------------------------------
573-- Top-level access to the node controller --
574--------------------------------------------------------------------------------
576runNodeController :: LocalNode -> IO ()
578 runReaderT (evalStateT (unNC nodeController) initNCState)
580--------------------------------------------------------------------------------
581-- Internal data types --
582--------------------------------------------------------------------------------
584data NCState = NCState
585 { -- Mapping from remote processes to linked local processes
586 _links :: !(Map Identifier (Set ProcessId))
587 -- Mapping from remote processes to monitoring local processes
588 , _monitors :: !(Map Identifier (Set (ProcessId, MonitorRef)))
589 -- Process registry: names and where they live, mapped to the PIDs
590 , _registeredHere :: !(Map String ProcessId)
591 , _registeredOnNodes :: !(Map ProcessId [(NodeId,Int)])
594newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
595 deriving (Functor, Monad, MonadIO, MonadState NCState, MonadReader LocalNode)
597initNCState :: NCState
598initNCState = NCState { _links = Map.empty
599 , _monitors = Map.empty
600 , _registeredHere = Map.empty
601 , _registeredOnNodes = Map.empty
604-- | Thrown in response to the user invoking 'kill' (see Primitives.hs). This
605-- type is deliberately not exported so it cannot be caught explicitly.
606data ProcessKillException =
607 ProcessKillException !ProcessId !String
610instance Exception ProcessKillException
611instance Show ProcessKillException where
612 show (ProcessKillException pid reason) =
613 "killed-by=" ++ show pid ++ ",reason=" ++ reason
615--------------------------------------------------------------------------------
616-- Tracing/Debugging --
617--------------------------------------------------------------------------------
619-- [Issue #104 / DP-13]
621traceNotifyDied :: LocalNode -> Identifier -> DiedReason -> NC ()
622traceNotifyDied node ident reason =
623 -- TODO: sendPortDied notifications
624 liftIO $ withLocalTracer node $ \t ->
626 (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
627 (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
630traceEventFmtIO :: LocalNode
634traceEventFmtIO node fmt args =
635 withLocalTracer node $ \t -> traceLogFmt t fmt args
637trace :: LocalNode -> MxEvent -> IO ()
638trace node ev = withLocalTracer node $ \t -> traceEvent t ev
640withLocalTracer :: LocalNode -> (MxEventBus -> IO ()) -> IO ()
641withLocalTracer node act = act (localEventBus node)
643--------------------------------------------------------------------------------
644-- Core functionality --
645--------------------------------------------------------------------------------
648nodeController :: NC ()
652 msg <- liftIO $ readChan (localCtrlChan node)
654 -- [Unified: Table 7, rule nc_forward]
655 case destNid (ctrlMsgSignal msg) of
656 Just nid' | nid' /= localNodeId node ->
657 liftIO $ sendBinary node
659 (NodeIdentifier nid')
660 WithImplicitReconnect
666 NCMsg (ProcessIdentifier from) (Link them) ->
667 ncEffectMonitor from them Nothing
668 NCMsg (ProcessIdentifier from) (Monitor ref) ->
669 ncEffectMonitor from (monitorRefIdent ref) (Just ref)
670 NCMsg (ProcessIdentifier from) (Unlink them) ->
671 ncEffectUnlink from them
672 NCMsg (ProcessIdentifier from) (Unmonitor ref) ->
673 ncEffectUnmonitor from ref
674 NCMsg _from (Died ident reason) ->
675 ncEffectDied ident reason
676 NCMsg (ProcessIdentifier from) (Spawn proc ref) ->
677 ncEffectSpawn from proc ref
678 NCMsg (ProcessIdentifier from) (Register label atnode pid force) ->
679 ncEffectRegister from label atnode pid force
680 NCMsg (ProcessIdentifier from) (WhereIs label) ->
681 ncEffectWhereIs from label
682 NCMsg _ (NamedSend label msg') ->
683 ncEffectNamedSend label msg'
684 NCMsg _ (LocalSend to msg') ->
685 ncEffectLocalSend node to msg'
686 NCMsg _ (LocalPortSend to msg') ->
687 ncEffectLocalPortSend to msg'
688 NCMsg (ProcessIdentifier from) (Kill to reason) ->
689 ncEffectKill from to reason
690 NCMsg (ProcessIdentifier from) (Exit to reason) ->
691 ncEffectExit from to reason
692 NCMsg (ProcessIdentifier from) (GetInfo pid) ->
693 ncEffectGetInfo from pid
694 NCMsg _ SigShutdown ->
696 NT.closeEndPoint (localEndPoint node)
697 `Exception.finally` throwIO ThreadKilled
698 -- ThreadKilled seems to make more sense than fail/error here
699 NCMsg (ProcessIdentifier from) (GetNodeStats nid) ->
700 ncEffectGetNodeStats from nid
702 error $ "nodeController: unexpected message " ++ show unexpected
704-- [Unified: Table 10]
705ncEffectMonitor :: ProcessId -- ^ Who's watching?
706 -> Identifier -- ^ Who's being watched?
707 -> Maybe MonitorRef -- ^ 'Nothing' to link
709ncEffectMonitor from them mRef = do
712 if not (isLocal node them)
714 else isValidLocalIdentifier them
715 case (shouldLink, isLocal node (ProcessIdentifier from)) of
716 (True, _) -> -- [Unified: first rule]
718 Just ref -> modify' $ monitorsFor them ^: Set.insert (from, ref)
719 Nothing -> modify' $ linksFor them ^: Set.insert from
720 (False, True) -> -- [Unified: second rule]
721 notifyDied from them DiedUnknownId mRef
722 (False, False) -> -- [Unified: third rule]
723 -- TODO: this is the right sender according to the Unified semantics,
724 -- but perhaps having 'them' as the sender would make more sense
725 -- (see also: notifyDied)
726 liftIO $ sendBinary node
727 (NodeIdentifier $ localNodeId node)
728 (NodeIdentifier $ processNodeId from)
729 WithImplicitReconnect
731 { ctrlMsgSender = NodeIdentifier (localNodeId node)
732 , ctrlMsgSignal = Died them DiedUnknownId
735-- [Unified: Table 11]
736ncEffectUnlink :: ProcessId -> Identifier -> NC ()
737ncEffectUnlink from them = do
739 when (isLocal node (ProcessIdentifier from)) $
741 ProcessIdentifier pid ->
742 postAsMessage from $ DidUnlinkProcess pid
743 NodeIdentifier nid ->
744 postAsMessage from $ DidUnlinkNode nid
745 SendPortIdentifier cid ->
746 postAsMessage from $ DidUnlinkPort cid
747 modify' $ linksFor them ^: Set.delete from
749-- [Unified: Table 11]
750ncEffectUnmonitor :: ProcessId -> MonitorRef -> NC ()
751ncEffectUnmonitor from ref = do
753 when (isLocal node (ProcessIdentifier from)) $
754 postAsMessage from $ DidUnmonitor ref
755 modify' $ monitorsFor (monitorRefIdent ref) ^: Set.delete (from, ref)
757-- [Unified: Table 12]
758ncEffectDied :: Identifier -> DiedReason -> NC ()
759ncEffectDied ident reason = do
761 traceNotifyDied node ident reason
762 (affectedLinks, unaffectedLinks) <- gets (splitNotif ident . (^. links))
763 (affectedMons, unaffectedMons) <- gets (splitNotif ident . (^. monitors))
765-- _registry :: !(Map (String,NodeId) ProcessId)
767 let localOnly = case ident of NodeIdentifier _ -> True ; _ -> False
769 forM_ (Map.toList affectedLinks) $ \(them, uss) ->
771 when (localOnly <= isLocal node (ProcessIdentifier us)) $
772 notifyDied us them reason Nothing
774 forM_ (Map.toList affectedMons) $ \(them, refs) ->
775 forM_ refs $ \(us, ref) ->
776 when (localOnly <= isLocal node (ProcessIdentifier us)) $
777 notifyDied us them reason (Just ref)
779 modify' $ (links ^= unaffectedLinks) . (monitors ^= unaffectedMons)
781 modify' $ registeredHere ^: Map.filter (\pid -> not $ ident `impliesDeathOf` ProcessIdentifier pid)
783 remaining <- fmap Map.toList (gets (^. registeredOnNodes)) >>=
784 mapM (\(pid,nidlist) ->
785 case ident `impliesDeathOf` ProcessIdentifier pid of
787 do forM_ nidlist $ \(nid,_) ->
788 when (not $ isLocal node (NodeIdentifier nid))
789 (forwardNameDeath node nid)
791 False -> return $ Just (pid,nidlist) )
792 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
794 forwardNameDeath node nid =
795 liftIO $ sendBinary node
796 (NodeIdentifier $ localNodeId node)
797 (NodeIdentifier $ nid)
798 WithImplicitReconnect
800 { ctrlMsgSender = NodeIdentifier (localNodeId node)
801 , ctrlMsgSignal = Died ident reason
804-- [Unified: Table 13]
805ncEffectSpawn :: ProcessId -> Closure (Process ()) -> SpawnRef -> NC ()
806ncEffectSpawn pid cProc ref = do
807 mProc <- unClosure cProc
808 -- If the closure does not exist, we spawn a process that throws an exception
809 -- This allows the remote node to find out what's happening
811 let proc = case mProc of
812 Left err -> fail $ "Error: Could not resolve closure: " ++ err
815 pid' <- liftIO $ forkProcess node proc
816 liftIO $ sendMessage node
817 (NodeIdentifier (localNodeId node))
818 (ProcessIdentifier pid)
819 WithImplicitReconnect
822-- Unified semantics does not explicitly describe how to implement 'register',
823-- but mentions it's "very similar to nsend" (Table 14)
824-- We send a response indicated if the operation is invalid
825ncEffectRegister :: ProcessId -> String -> NodeId -> Maybe ProcessId -> Bool -> NC ()
826ncEffectRegister from label atnode mPid reregistration = do
828 currentVal <- gets (^. registeredHereFor label)
831 Nothing -> -- unregister request
832 return $ isJust currentVal
833 Just thepid -> -- register request
834 do isvalidlocal <- isValidLocalIdentifier (ProcessIdentifier thepid)
835 return $ (isNothing currentVal /= reregistration) &&
836 (not (isLocal node (ProcessIdentifier thepid) ) || isvalidlocal )
837 if isLocal node (NodeIdentifier atnode)
838 then do when (isOk) $
839 do modify' $ registeredHereFor label ^= mPid
840 updateRemote node currentVal mPid
842 (Just p) -> liftIO $ trace node (MxRegistered p label)
843 Nothing -> liftIO $ trace node (MxUnRegistered (fromJust currentVal) label)
844 liftIO $ sendMessage node
845 (NodeIdentifier (localNodeId node))
846 (ProcessIdentifier from)
847 WithImplicitReconnect
848 (RegisterReply label isOk)
850 case reregistration of
852 False -> flip incList
855 Just pid -> modify' $ registeredOnNodesFor pid ^: (maybeify $ operation atnode)
856 where updateRemote node (Just oldval) (Just newval) | processNodeId oldval /= processNodeId newval =
857 do forward node (processNodeId oldval) (Register label atnode (Just oldval) True)
858 forward node (processNodeId newval) (Register label atnode (Just newval) False)
859 updateRemote node Nothing (Just newval) =
860 forward node (processNodeId newval) (Register label atnode (Just newval) False)
861 updateRemote node (Just oldval) Nothing =
862 forward node (processNodeId oldval) (Register label atnode (Just oldval) True)
863 updateRemote _ _ _ = return ()
864 maybeify f Nothing = unmaybeify $ f []
865 maybeify f (Just x) = unmaybeify $ f x
867 unmaybeify [] = Nothing
868 unmaybeify x = Just x
869 incList [] tag = [(tag,1)]
870 incList ((atag,acount):xs) tag | tag==atag = (atag,acount+1) : xs
871 incList (x:xs) tag = x : incList xs tag
873 decList ((atag,1):xs) tag | atag == tag = xs
874 decList ((atag,n):xs) tag | atag == tag = (atag,n-1):xs
875 decList (x:xs) tag = x:decList xs tag
876 forward node to reg =
877 when (not $ isLocal node (NodeIdentifier to)) $
878 liftIO $ sendBinary node
879 (ProcessIdentifier from)
881 WithImplicitReconnect
883 { ctrlMsgSender = ProcessIdentifier from
884 , ctrlMsgSignal = reg
888-- Unified semantics does not explicitly describe 'whereis'
889ncEffectWhereIs :: ProcessId -> String -> NC ()
890ncEffectWhereIs from label = do
892 mPid <- gets (^. registeredHereFor label)
893 liftIO $ sendMessage node
894 (NodeIdentifier (localNodeId node))
895 (ProcessIdentifier from)
896 WithImplicitReconnect
897 (WhereIsReply label mPid)
899-- [Unified: Table 14]
900ncEffectNamedSend :: String -> Message -> NC ()
901ncEffectNamedSend label msg = do
902 mPid <- gets (^. registeredHereFor label)
903 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
904 forM_ mPid $ \pid -> postMessage pid msg
907ncEffectLocalSend :: LocalNode -> ProcessId -> Message -> NC ()
908ncEffectLocalSend node to msg =
909 liftIO $ withLocalProc node to $ \p -> do
910 enqueue (processQueue p) msg
911 trace node (MxReceived to msg)
914ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
915ncEffectLocalPortSend from msg = do
917 let pid = sendPortProcessId from
918 cid = sendPortLocalId from
919 liftIO $ withLocalProc node pid $ \proc -> do
920 mChan <- withMVar (processState proc) $ return . (^. typedChannelWithId cid)
922 -- in the unlikely event we know nothing about this channel id,
923 -- there's little to be done - perhaps some logging/tracing though...
925 Just (TypedChannel chan') -> do
926 -- If ch is Nothing, the process has given up the read end of
927 -- the channel and we simply ignore the incoming message - this
928 ch <- deRefWeak chan'
929 forM_ ch $ \chan -> deliverChan msg chan
930 where deliverChan :: forall a . Message -> TQueue a -> IO ()
931 deliverChan (UnencodedMessage _ raw) chan' =
932 atomically $ writeTQueue chan' ((unsafeCoerce raw) :: a)
933 deliverChan (EncodedMessage _ _) _ =
934 -- this will not happen unless someone screws with Primitives.hs
935 error "invalid local channel delivery"
938ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
939ncEffectKill from to reason = do
941 when (isLocal node (ProcessIdentifier to)) $
942 throwException to $ ProcessKillException from reason
945ncEffectExit :: ProcessId -> ProcessId -> Message -> NC ()
946ncEffectExit from to reason = do
948 when (isLocal node (ProcessIdentifier to)) $
949 throwException to $ ProcessExitException from reason
952ncEffectGetInfo :: ProcessId -> ProcessId -> NC ()
953ncEffectGetInfo from pid =
954 let lpid = processLocalId pid
955 them = (ProcessIdentifier pid)
959 withMVar (localState node) $ return . (^. localProcessWithId lpid)
961 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
962 from node (ProcessInfoNone DiedUnknownId)
964 itsLinks <- gets (^. linksFor them)
965 itsMons <- gets (^. monitorsFor them)
966 registered <- gets (^. registeredHere)
968 let reg = registeredNames registered
969 dispatch (isLocal node (ProcessIdentifier from))
973 infoNode = (processNodeId pid)
974 , infoRegisteredNames = reg
975 -- we cannot populate this field
976 , infoMessageQueueLength = Nothing
977 , infoMonitors = Set.toList itsMons
978 , infoLinks = Set.toList itsLinks
980 where dispatch :: (Serializable a, Show a)
986 dispatch True dest _ pInfo = postAsMessage dest $ pInfo
987 dispatch False dest node pInfo = do
988 liftIO $ sendMessage node
989 (NodeIdentifier (localNodeId node))
990 (ProcessIdentifier dest)
991 WithImplicitReconnect
994 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
998ncEffectGetNodeStats :: ProcessId -> NodeId -> NC ()
999ncEffectGetNodeStats from _nid = do
1001 ncState <- StateT.get
1002 nodeState <- liftIO $ readMVar (localState node)
1003 let localProcesses' = nodeState ^. localProcesses
1006 nodeStatsNode = localNodeId node
1007 , nodeStatsRegisteredNames = Map.size $ ncState ^. registeredHere
1008 , nodeStatsMonitors = Map.size $ ncState ^. monitors
1009 , nodeStatsLinks = Map.size $ ncState ^. links
1010 , nodeStatsProcesses = Map.size localProcesses'
1012 postAsMessage from stats
1013--------------------------------------------------------------------------------
1015--------------------------------------------------------------------------------
1017notifyDied :: ProcessId -- ^ Who to notify?
1018 -> Identifier -- ^ Who died?
1019 -> DiedReason -- ^ How did they die?
1020 -> Maybe MonitorRef -- ^ 'Nothing' for linking
1022notifyDied dest src reason mRef = do
1024 case (isLocal node (ProcessIdentifier dest), mRef, src) of
1025 (True, Just ref, ProcessIdentifier pid) ->
1026 postAsMessage dest $ ProcessMonitorNotification ref pid reason
1027 (True, Just ref, NodeIdentifier nid) ->
1028 postAsMessage dest $ NodeMonitorNotification ref nid reason
1029 (True, Just ref, SendPortIdentifier cid) ->
1030 postAsMessage dest $ PortMonitorNotification ref cid reason
1031 (True, Nothing, ProcessIdentifier pid) ->
1032 throwException dest $ ProcessLinkException pid reason
1033 (True, Nothing, NodeIdentifier pid) ->
1034 throwException dest $ NodeLinkException pid reason
1035 (True, Nothing, SendPortIdentifier pid) ->
1036 throwException dest $ PortLinkException pid reason
1038 -- The change in sender comes from [Unified: Table 10]
1039 liftIO $ sendBinary node
1040 (NodeIdentifier $ localNodeId node)
1041 (NodeIdentifier $ processNodeId dest)
1042 WithImplicitReconnect
1044 { ctrlMsgSender = NodeIdentifier (localNodeId node)
1045 , ctrlMsgSignal = Died src reason
1048-- | [Unified: Table 8]
1049destNid :: ProcessSignal -> Maybe NodeId
1050destNid (Link ident) = Just $ nodeOf ident
1051destNid (Unlink ident) = Just $ nodeOf ident
1052destNid (Monitor ref) = Just $ nodeOf (monitorRefIdent ref)
1053destNid (Unmonitor ref) = Just $ nodeOf (monitorRefIdent ref)
1054destNid (Spawn _ _) = Nothing
1055destNid (Register _ _ _ _) = Nothing
1056destNid (WhereIs _) = Nothing
1057destNid (NamedSend _ _) = Nothing
1058-- We don't need to forward 'Died' signals; if monitoring/linking is setup,
1059-- then when a local process dies the monitoring/linking machinery will take
1060-- care of notifying remote nodes
1061destNid (Died _ _) = Nothing
1062destNid (Kill pid _) = Just $ processNodeId pid
1063destNid (Exit pid _) = Just $ processNodeId pid
1064destNid (GetInfo pid) = Just $ processNodeId pid
1065destNid (GetNodeStats nid) = Just nid
1066destNid (LocalSend pid _) = Just $ processNodeId pid
1067destNid (LocalPortSend cid _) = Just $ processNodeId (sendPortProcessId cid)
1068destNid (SigShutdown) = Nothing
1070-- | Check if a process is local to our own node
1071isLocal :: LocalNode -> Identifier -> Bool
1072isLocal nid ident = nodeOf ident == localNodeId nid
1074-- | Lookup a local closure
1075unClosure :: Typeable a => Closure a -> NC (Either String a)
1076unClosure closure = do
1077 rtable <- remoteTable <$> ask
1078 return (Static.unclosure rtable closure)
1080-- | Check if an identifier refers to a valid local object
1081isValidLocalIdentifier :: Identifier -> NC Bool
1082isValidLocalIdentifier ident = do
1084 liftIO . withMVar (localState node) $ \nSt ->
1086 NodeIdentifier nid ->
1087 return $ nid == localNodeId node
1088 ProcessIdentifier pid -> do
1089 let mProc = nSt ^. localProcessWithId (processLocalId pid)
1090 return $ isJust mProc
1091 SendPortIdentifier cid -> do
1092 let pid = sendPortProcessId cid
1093 mProc = nSt ^. localProcessWithId (processLocalId pid)
1095 Nothing -> return False
1096 Just proc -> withMVar (processState proc) $ \pSt -> do
1097 let mCh = pSt ^. typedChannelWithId (sendPortLocalId cid)
1100--------------------------------------------------------------------------------
1101-- Messages to local processes --
1102--------------------------------------------------------------------------------
1104postAsMessage :: Serializable a => ProcessId -> a -> NC ()
1105postAsMessage pid = postMessage pid . createUnencodedMessage
1107postMessage :: ProcessId -> Message -> NC ()
1108postMessage pid msg = do
1110 liftIO $ withLocalProc node pid $ \p -> enqueue (processQueue p) msg
1112throwException :: Exception e => ProcessId -> e -> NC ()
1113throwException pid e = do
1115 liftIO $ withLocalProc node pid $ \p -> throwTo (processThread p) e
1117withLocalProc :: LocalNode -> ProcessId -> (LocalProcess -> IO ()) -> IO ()
1118withLocalProc node pid p =
1119 -- By [Unified: table 6, rule missing_process] messages to dead processes
1120 -- can silently be dropped
1121 let lpid = processLocalId pid in do
1122 mProc <- withMVar (localState node) $ return . (^. localProcessWithId lpid)
1125--------------------------------------------------------------------------------
1127--------------------------------------------------------------------------------
1129links :: Accessor NCState (Map Identifier (Set ProcessId))
1130links = accessor _links (\ls st -> st { _links = ls })
1132monitors :: Accessor NCState (Map Identifier (Set (ProcessId, MonitorRef)))
1133monitors = accessor _monitors (\ms st -> st { _monitors = ms })
1135registeredHere :: Accessor NCState (Map String ProcessId)
1136registeredHere = accessor _registeredHere (\ry st -> st { _registeredHere = ry })
1138registeredOnNodes :: Accessor NCState (Map ProcessId [(NodeId, Int)])
1139registeredOnNodes = accessor _registeredOnNodes (\ry st -> st { _registeredOnNodes = ry })
1141linksFor :: Identifier -> Accessor NCState (Set ProcessId)
1142linksFor ident = links >>> DAC.mapDefault Set.empty ident
1144monitorsFor :: Identifier -> Accessor NCState (Set (ProcessId, MonitorRef))
1145monitorsFor ident = monitors >>> DAC.mapDefault Set.empty ident
1147registeredHereFor :: String -> Accessor NCState (Maybe ProcessId)
1148registeredHereFor ident = registeredHere >>> DAC.mapMaybe ident
1150registeredOnNodesFor :: ProcessId -> Accessor NCState (Maybe [(NodeId,Int)])
1151registeredOnNodesFor ident = registeredOnNodes >>> DAC.mapMaybe ident
1153-- | @splitNotif ident@ splits a notifications map into those
1154-- notifications that should trigger when 'ident' fails and those links that
1157-- There is a hierarchy between identifiers: failure of a node implies failure
1158-- of all processes on that node, and failure of a process implies failure of
1159-- all typed channels to that process. In other words, if 'ident' refers to a
1160-- node, then the /should trigger/ set will include
1162-- * the notifications for the node specifically
1163-- * the notifications for processes on that node, and
1164-- * the notifications for typed channels to processes on that node.
1166-- Similarly, if 'ident' refers to a process, the /should trigger/ set will
1169-- * the notifications for that process specifically and
1170-- * the notifications for typed channels to that process.
1172-- See https://github.com/haskell/containers/issues/14 for the bang on _v.
1173splitNotif :: Identifier
1175 -> (Map Identifier a, Map Identifier a)
1176splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1178--------------------------------------------------------------------------------
1180--------------------------------------------------------------------------------
1182-- | Modify and evaluate the state
1183modify' :: MonadState s m => (s -> s) -> m ()
1184modify' f = StateT.get >>= \s -> StateT.put $! f s
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list