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 (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)
67 , uninterruptibleMask_
69import qualified Control.Exception as Exception (Handler(..), catches, finally)
70import Control.Concurrent (forkIO, forkIOWithUnmask, killThread, myThreadId)
71import 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
92import qualified Network.Transport as NT
106 , Reliability(ReliableOrdered)
108import Data.Accessor (Accessor, accessor, (^.), (^=), (^:))
109import System.Random (randomIO)
110import Control.Distributed.Static (RemoteTable, Closure)
111import qualified Control.Distributed.Static as Static
115import Control.Distributed.Process.Internal.Types
122 , ValidLocalNodeState(..)
123 , withValidLocalState
124 , modifyValidLocalState
126 , LocalProcessState(..)
138 , ProcessMonitorNotification(..)
139 , NodeMonitorNotification(..)
140 , PortMonitorNotification(..)
141 , ProcessExitException(..)
142 , ProcessLinkException(..)
143 , NodeLinkException(..)
144 , PortLinkException(..)
146 , DidUnlinkProcess(..)
156 , ProcessInfoNone(..)
164 , createUnencodedMessage
166 , firstNonReservedProcessId
167 , ImplicitReconnect(WithImplicitReconnect,NoImplicitReconnect)
169import Control.Distributed.Process.Management.Internal.Agent
172import qualified Control.Distributed.Process.Management.Internal.Table as Table
174 , startTableCoordinator
176import qualified Control.Distributed.Process.Management.Internal.Trace.Remote as Trace
179import Control.Distributed.Process.Management.Internal.Trace.Tracer
182import Control.Distributed.Process.Management.Internal.Trace.Types
188import Control.Distributed.Process.Management.Internal.Types
191import Control.Distributed.Process.Serializable (Serializable)
192import Control.Distributed.Process.Internal.Messaging
196 , closeImplicitReconnections
199import Control.Distributed.Process.Internal.Primitives
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
217--------------------------------------------------------------------------------
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
229 Left ex -> throwIO ex
231 localNode <- createBareLocalNode endPoint rtable
232 startServiceProcesses localNode
235-- | Create a new local node (without any service processes running)
236createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
237createBareLocalNode endPoint rtable = do
239 state <- newMVar $ LocalNodeValid $ ValidLocalNodeState
240 { _localProcesses = Map.empty
241 , _localPidCounter = firstNonReservedProcessId
242 , _localPidUnique = unq
243 , _localConnections = Map.empty
246 let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
247 , localEndPoint = endPoint
249 , localCtrlChan = ctrlChan
250 , localEventBus = MxEventBusInitialising
251 , remoteTable = rtable
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)
266 writeChan (localCtrlChan node) NCMsg
267 { ctrlMsgSender = NodeIdentifier (localNodeId node)
268 , ctrlMsgSignal = SigShutdown
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'
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'
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
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
311 fork = forkProcess node
315 [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
316 liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
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
322 , match $ \(ch :: SendPort ()) -> -- a shutdown request
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
348 void $ forkProcess node $ do
349 catch (proc `finally` liftIO (putMVar done ()))
350 (\(ex :: SomeException) -> liftIO $ throwTo tid ex)
353-- | Spawn a new process on a local node
354forkProcess :: LocalNode -> Process () -> IO ProcessId
355forkProcess node proc =
356 modifyMVarMasked (localState node) startProcess
358 startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
359 startProcess (LocalNodeValid vst) = do
360 let lpid = LocalProcessId { lpidCounter = vst ^. localPidCounter
361 , lpidUnique = vst ^. localPidUnique
363 let pid = ProcessId { processNodeId = localNodeId node
364 , processLocalId = lpid
366 pst <- newMVar LocalProcessState { _monitorCounter = 0
368 , _channelCounter = 0
369 , _typedChannels = Map.empty
372 weakQueue <- mkWeakCQueue queue (return ())
373 (_, lproc) <- fixIO $ \ ~(tid, _) -> do
374 let lproc = LocalProcess { processQueue = queue
375 , processWeakQ = weakQueue
378 , processThread = tid
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)
387 Nothing -> return $ DiedException $ show ex
388 Just m -> return $ DiedException ("exit-from=" ++ (show from) ++ ",reason=" ++ m)))
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
405 -- see note [tracer/forkProcess races]
406 trace node (MxSpawned pid)
408 if lpidCounter lpid == maxBound
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)
421 return ( LocalNodeValid
422 $ (localProcessWithId lpid ^= Just lproc)
423 . (localPidCounter ^: (+ 1))
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)
438 , map fst $ Map.elems affected
441-- note [tracer/forkProcess races]
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).
450--------------------------------------------------------------------------------
451-- Handle incoming messages --
452--------------------------------------------------------------------------------
454type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
458 | ToProc ProcessId (Weak (CQueue Message))
459 | ToChan TypedChannel
462data ConnectionState = ConnectionState {
463 _incoming :: !(Map NT.ConnectionId IncomingConnection)
464 , _incomingFrom :: !(Map NT.EndPointAddress (Set NT.ConnectionId))
467initConnectionState :: ConnectionState
468initConnectionState = ConnectionState {
469 _incoming = Map.empty
470 , _incomingFrom = Map.empty
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
482 aux = accessor _incomingFrom (\fr st -> st { _incomingFrom = fr })
484handleIncomingMessages :: LocalNode -> IO ()
485handleIncomingMessages node = go initConnectionState
487 go :: ConnectionState -> IO ()
489 event <- NT.receive endpoint
491 NT.ConnectionOpened cid rel theirAddr ->
492 if rel == NT.ReliableOrdered
494 trace node (MxConnected cid theirAddr)
496 (incomingAt cid ^= Just (theirAddr, Uninit))
497 . (incomingFrom theirAddr ^: Set.insert cid)
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)
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)
520 Just (_, ToNode) -> do
521 let ctrlMsg = decode . BSL.fromChunks $ payload
522 writeChan ctrlChan $! ctrlMsg
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)
531 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
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)
540 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
543 go (incomingAt cid ^= Just (src, ToChan channel) $ st)
545 invalidRequest cid st
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
553 invalidRequest cid st
554 NT.ConnectionClosed cid ->
555 case st ^. incomingAt cid of
557 invalidRequest cid st
559 trace node (MxDisconnected cid src)
560 go ( (incomingAt cid ^= Nothing)
561 . (incomingFrom src ^: Set.delete cid)
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
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))
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
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
594 traceEventFmtIO node "" [(TraceStr " [network] invalid request: "),
596 go ( incomingAt cid ^= Nothing
600 endpoint = localEndPoint node
601 ctrlChan = localCtrlChan node
603--------------------------------------------------------------------------------
604-- Top-level access to the node controller --
605--------------------------------------------------------------------------------
607runNodeController :: LocalNode -> IO ()
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)])
625newtype NC a = NC { unNC :: StateT NCState (ReaderT LocalNode IO) a }
626 deriving ( Applicative
631 , MonadReader LocalNode
634initNCState :: NCState
635initNCState = NCState { _links = Map.empty
636 , _monitors = Map.empty
637 , _registeredHere = Map.empty
638 , _registeredOnNodes = Map.empty
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
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 ->
663 (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
664 (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
667traceEventFmtIO :: LocalNode
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--------------------------------------------------------------------------------
685nodeController :: NC ()
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
696 (NodeIdentifier nid')
697 WithImplicitReconnect
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 ->
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
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
748ncEffectMonitor from them mRef = do
751 if not (isLocal node them)
753 else isValidLocalIdentifier them
754 case (shouldLink, isLocal node (ProcessIdentifier from)) of
755 (True, _) -> -- [Unified: first rule]
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
770 { ctrlMsgSender = NodeIdentifier (localNodeId node)
771 , ctrlMsgSignal = Died them DiedUnknownId
774-- [Unified: Table 11]
775ncEffectUnlink :: ProcessId -> Identifier -> NC ()
776ncEffectUnlink from them = do
778 when (isLocal node (ProcessIdentifier from)) $
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
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
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) ->
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
826 do forM_ nidlist $ \(nid,_) ->
827 when (not $ isLocal node (NodeIdentifier nid))
828 (forwardNameDeath node nid)
830 False -> return $ Just (pid,nidlist) )
831 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
833 forwardNameDeath node nid =
834 liftIO $ sendBinary node
835 (NodeIdentifier $ localNodeId node)
836 (NodeIdentifier $ nid)
837 WithImplicitReconnect
839 { ctrlMsgSender = NodeIdentifier (localNodeId node)
840 , ctrlMsgSignal = Died ident reason
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
850 let proc = case mProc of
851 Left err -> fail $ "Error: Could not resolve closure: " ++ err
854 pid' <- liftIO $ forkProcess node proc
855 liftIO $ sendMessage node
856 (NodeIdentifier (localNodeId node))
857 (ProcessIdentifier pid)
858 WithImplicitReconnect
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
867 currentVal <- gets (^. registeredHereFor label)
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)
878 do modify' $ registeredHereFor label ^= mPid
879 updateRemote node currentVal mPid
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)
890 case reregistration of
892 False -> flip incList
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
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)
921 WithImplicitReconnect
923 { ctrlMsgSender = ProcessIdentifier from
924 , ctrlMsgSignal = reg
928-- Unified semantics does not explicitly describe 'whereis'
929ncEffectWhereIs :: ProcessId -> String -> NC ()
930ncEffectWhereIs from label = do
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)
944 -- If mPid is Nothing, we just ignore the named send (as per Table 14)
946 liftIO $ sendPayload node
947 (ProcessIdentifier from)
948 (ProcessIdentifier pid)
950 (messageToPayload msg)
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)
960ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
961ncEffectLocalPortSend from msg = do
963 let pid = sendPortProcessId from
964 cid = sendPortLocalId from
965 liftIO $ withLocalProc node pid $ \proc -> do
966 mChan <- withMVar (processState proc) $ return . (^. typedChannelWithId cid)
968 -- in the unlikely event we know nothing about this channel id,
969 -- there's little to be done - perhaps some logging/tracing though...
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"
984ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
985ncEffectKill from to reason = do
987 when (isLocal node (ProcessIdentifier to)) $
988 throwException to $ ProcessKillException from reason
991ncEffectExit :: ProcessId -> ProcessId -> Message -> NC ()
992ncEffectExit from to reason = do
994 when (isLocal node (ProcessIdentifier to)) $
995 throwException to $ ProcessExitException from reason
998ncEffectGetInfo :: ProcessId -> ProcessId -> NC ()
999ncEffectGetInfo from pid =
1000 let lpid = processLocalId pid
1001 them = (ProcessIdentifier pid)
1004 mProc <- liftIO $ withValidLocalState node
1005 $ return . (^. localProcessWithId lpid)
1007 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
1008 from node (ProcessInfoNone DiedUnknownId)
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))
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)
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
1040 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
1044ncEffectGetNodeStats :: ProcessId -> NodeId -> NC ()
1045ncEffectGetNodeStats from _nid = do
1047 ncState <- StateT.get
1048 nodeState <- liftIO $ withValidLocalState node return
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--------------------------------------------------------------------------------
1061--------------------------------------------------------------------------------
1063notifyDied :: ProcessId -- ^ Who to notify?
1064 -> Identifier -- ^ Who died?
1065 -> DiedReason -- ^ How did they die?
1066 -> Maybe MonitorRef -- ^ 'Nothing' for linking
1068notifyDied dest src reason mRef = do
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
1084 -- The change in sender comes from [Unified: Table 10]
1085 liftIO $ sendBinary node
1086 (NodeIdentifier $ localNodeId node)
1087 (NodeIdentifier $ processNodeId dest)
1088 WithImplicitReconnect
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
1131 liftIO . withValidLocalState node $ \nSt ->
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)
1142 Nothing -> return False
1143 Just proc -> withMVar (processState proc) $ \pSt -> do
1144 let mCh = pSt ^. typedChannelWithId (sendPortLocalId cid)
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
1157 liftIO $ withLocalProc node pid $ \p -> enqueue (processQueue p) msg
1159throwException :: Exception e => ProcessId -> e -> NC ()
1160throwException pid e = do
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--------------------------------------------------------------------------------
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
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
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
1224 -> (Map Identifier a, Map Identifier a)
1225splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1227--------------------------------------------------------------------------------
1229--------------------------------------------------------------------------------
1231-- | Modify and evaluate the state
1232modify' :: MonadState s m => (s -> s) -> m ()
1233modify' 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