git.iko.soy/distributed-process
on 0fae299 help sign in
1184 lines 47 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 ((<$>))
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 )
68import qualified Control.Exception as Exception (Handler(..), catches, finally)
69import Control.Concurrent (forkIO, myThreadId)
70import Control.Distributed.Process.Internal.StrictMVar
71 ( newMVar
72 , withMVar
73 , modifyMVar
74 , modifyMVar_
75 , newEmptyMVar
76 , putMVar
77 , takeMVar
78 , readMVar
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 )
91import qualified Network.Transport as NT
92 ( Transport
93 , EndPoint
94 , newEndPoint
95 , receive
96 , Event(..)
97 , EventErrorCode(..)
98 , TransportError(..)
99 , address
100 , closeEndPoint
101 , ConnectionId
102 , Connection
103 , close
104 , EndPointAddress
105 , Reliability(ReliableOrdered)
106 )
107import Data.Accessor (Accessor, accessor, (^.), (^=), (^:))
108import System.Random (randomIO)
109import Control.Distributed.Static (RemoteTable, Closure)
110import qualified Control.Distributed.Static as Static
111 ( unclosure
112 , initRemoteTable
113 )
114import Control.Distributed.Process.Internal.Types
115 ( NodeId(..)
116 , LocalProcessId(..)
117 , ProcessId(..)
118 , LocalNode(..)
119 , MxEventBus(..)
120 , LocalNodeState(..)
121 , LocalProcess(..)
122 , LocalProcessState(..)
123 , Process(..)
124 , DiedReason(..)
125 , NCMsg(..)
126 , ProcessSignal(..)
127 , localPidCounter
128 , localPidUnique
129 , localProcessWithId
130 , localProcesses
131 , localConnections
132 , forever'
133 , MonitorRef(..)
134 , ProcessMonitorNotification(..)
135 , NodeMonitorNotification(..)
136 , PortMonitorNotification(..)
137 , ProcessExitException(..)
138 , ProcessLinkException(..)
139 , NodeLinkException(..)
140 , PortLinkException(..)
141 , DidUnmonitor(..)
142 , DidUnlinkProcess(..)
143 , DidUnlinkNode(..)
144 , DidUnlinkPort(..)
145 , SpawnRef
146 , DidSpawn(..)
147 , Message(..)
148 , TypedChannel(..)
149 , Identifier(..)
150 , nodeOf
151 , ProcessInfo(..)
152 , ProcessInfoNone(..)
153 , NodeStats(..)
154 , SendPortId(..)
155 , typedChannelWithId
156 , RegisterReply(..)
157 , WhereIsReply(..)
158 , payloadToMessage
159 , createUnencodedMessage
160 , runLocalProcess
161 , firstNonReservedProcessId
162 , ImplicitReconnect(WithImplicitReconnect)
163 )
164import Control.Distributed.Process.Management.Internal.Agent
165 ( mxAgentController
166 )
167import qualified Control.Distributed.Process.Management.Internal.Table as Table
168 ( mxTableCoordinator
169 , startTableCoordinator
170 )
171import qualified Control.Distributed.Process.Management.Internal.Trace.Remote as Trace
172 ( remoteTable
173 )
174import Control.Distributed.Process.Management.Internal.Trace.Tracer
175 ( defaultTracer
176 )
177import Control.Distributed.Process.Management.Internal.Trace.Types
178 ( TraceArg(..)
179 , traceEvent
180 , traceLogFmt
181 , enableTrace
182 )
183import Control.Distributed.Process.Management.Internal.Types
184 ( MxEvent(..)
185 )
186import Control.Distributed.Process.Serializable (Serializable)
187import Control.Distributed.Process.Internal.Messaging
188 ( sendBinary
189 , sendMessage
190 , closeImplicitReconnections
191 , impliesDeathOf
192 )
193import Control.Distributed.Process.Internal.Primitives
194 ( register
195 , finally
196 , receiveWait
197 , match
198 , sendChan
199 , catch
200 , unwrapMessage
201 )
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
206 ( mapMaybe
207 , mapDefault
208 )
209import Unsafe.Coerce
211--------------------------------------------------------------------------------
212-- Initialization --
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
222 case mEndPoint of
223 Left ex -> throwIO ex
224 Right endPoint -> do
225 localNode <- createBareLocalNode endPoint rtable
226 startServiceProcesses localNode
227 return localNode
229-- | Create a new local node (without any service processes running)
230createBareLocalNode :: NT.EndPoint -> RemoteTable -> IO LocalNode
231createBareLocalNode endPoint rtable = do
232 unq <- randomIO
233 state <- newMVar LocalNodeState
234 { _localProcesses = Map.empty
235 , _localPidCounter = firstNonReservedProcessId
236 , _localPidUnique = unq
237 , _localConnections = Map.empty
238 }
239 ctrlChan <- newChan
240 let node = LocalNode { localNodeId = NodeId $ NT.address endPoint
241 , localEndPoint = endPoint
242 , localState = state
243 , localCtrlChan = ctrlChan
244 , localEventBus = MxEventBusInitialising
245 , remoteTable = rtable
246 }
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)
255 (stopNC node)
257 return tracedNode
258 where
259 stopNC node =
260 writeChan (localCtrlChan node) NCMsg
261 { ctrlMsgSender = NodeIdentifier (localNodeId node)
262 , ctrlMsgSignal = SigShutdown
263 }
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'
277 case t of
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'
283 _ -> return ()
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
299 where
300 fork = forkProcess node
302 loop = do
303 receiveWait
304 [ match $ \((time, pid, string) ::(String, ProcessId, String)) -> do
305 liftIO . hPutStrLn stderr $ time ++ " " ++ show pid ++ ": " ++ string
306 loop
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
310 loop
311 , match $ \(ch :: SendPort ()) -> -- a shutdown request
312 sendChan ch ()
313 ]
315-- | Force-close a local node
316--
317-- TODO: for now we just close the associated endpoint
318closeLocalNode :: LocalNode -> IO ()
319closeLocalNode node =
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
326 done <- newEmptyMVar
327 tid <- myThreadId
328 void $ forkProcess node $ do
329 catch (proc `finally` liftIO (putMVar done ()))
330 (\(ex :: SomeException) -> liftIO $ throwTo tid ex)
331 takeMVar done
333-- | Spawn a new process on a local node
334forkProcess :: LocalNode -> Process () -> IO ProcessId
335forkProcess node proc = modifyMVar (localState node) startProcess
336 where
337 startProcess :: LocalNodeState -> IO (LocalNodeState, ProcessId)
338 startProcess st = do
339 let lpid = LocalProcessId { lpidCounter = st ^. localPidCounter
340 , lpidUnique = st ^. localPidUnique
341 }
342 let pid = ProcessId { processNodeId = localNodeId node
343 , processLocalId = lpid
344 }
345 pst <- newMVar LocalProcessState { _monitorCounter = 0
346 , _spawnCounter = 0
347 , _channelCounter = 0
348 , _typedChannels = Map.empty
349 }
350 queue <- newCQueue
351 weakQueue <- mkWeakCQueue queue (return ())
352 (_, lproc) <- fixIO $ \ ~(tid, _) -> do
353 let lproc = LocalProcess { processQueue = queue
354 , processWeakQ = weakQueue
355 , processId = pid
356 , processState = pst
357 , processThread = tid
358 , processNode = node
359 }
360 tid' <- forkIO $ do
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)
365 case mMsg of
366 Nothing -> return $ DiedException $ show ex
367 Just m -> return $ DiedException ("exit-from=" ++ (show from) ++ ",reason=" ++ m)))
368 , (Exception.Handler
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
376 }
377 return (tid', lproc)
379 -- see note [tracer/forkProcess races]
380 trace node (MxSpawned pid)
382 if lpidCounter lpid == maxBound
383 then do
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)
390 $ st
391 , pid
392 )
393 else
394 return ( (localProcessWithId lpid ^= Just lproc)
395 . (localPidCounter ^: (+ 1))
396 $ st
397 , pid
398 )
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)
407 $ st
409-- note [tracer/forkProcess races]
410--
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).
416--
418--------------------------------------------------------------------------------
419-- Handle incoming messages --
420--------------------------------------------------------------------------------
422type IncomingConnection = (NT.EndPointAddress, IncomingTarget)
424data IncomingTarget =
425 Uninit
426 | ToProc ProcessId (Weak (CQueue Message))
427 | ToChan TypedChannel
428 | ToNode
430data ConnectionState = ConnectionState {
431 _incoming :: !(Map NT.ConnectionId IncomingConnection)
432 , _incomingFrom :: !(Map NT.EndPointAddress (Set NT.ConnectionId))
433 }
435initConnectionState :: ConnectionState
436initConnectionState = ConnectionState {
437 _incoming = Map.empty
438 , _incomingFrom = Map.empty
439 }
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
449 where
450 aux = accessor _incomingFrom (\fr st -> st { _incomingFrom = fr })
452handleIncomingMessages :: LocalNode -> IO ()
453handleIncomingMessages node = go initConnectionState
454 where
455 go :: ConnectionState -> IO ()
456 go !st = do
457 event <- NT.receive endpoint
458 case event of
459 NT.ConnectionOpened cid rel theirAddr ->
460 if rel == NT.ReliableOrdered
461 then
462 trace node (MxConnected cid theirAddr)
463 >> go (
464 (incomingAt cid ^= Just (theirAddr, Uninit))
465 . (incomingFrom theirAddr ^: Set.insert cid)
466 $ st
467 )
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)
479 go st
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)
487 go st
488 Just (_, ToNode) -> do
489 let ctrlMsg = decode . BSL.fromChunks $ payload
490 writeChan ctrlChan $! ctrlMsg
491 go st
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)
497 case mProc of
498 Just proc ->
499 go (incomingAt cid ^= Just (src, ToProc pid (processWeakQ proc)) $ st)
500 Nothing ->
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)
506 case mProc of
507 Just proc -> do
508 mChannel <- withMVar (processState proc) $ return . (^. typedChannelWithId lcid)
509 case mChannel of
510 Just channel ->
511 go (incomingAt cid ^= Just (src, ToChan channel) $ st)
512 Nothing ->
513 invalidRequest cid st
514 Nothing ->
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
520 Nothing ->
521 invalidRequest cid st
522 NT.ConnectionClosed cid ->
523 case st ^. incomingAt cid of
524 Nothing ->
525 invalidRequest cid st
526 Just (src, _) -> do
527 trace node (MxDisconnected cid src)
528 go ( (incomingAt cid ^= Nothing)
529 . (incomingFrom src ^: Set.delete cid)
530 $ st
531 )
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
538 }
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))
543 $ st
544 )
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
549 NT.EndPointClosed ->
550 return ()
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
561 -- extension).
562 traceEventFmtIO node "" [(TraceStr " [network] invalid request: "),
563 (Trace cid)]
564 go ( incomingAt cid ^= Nothing
565 $ st
566 )
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 ()
577runNodeController =
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)])
592 }
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
602 }
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
608 deriving (Typeable)
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 ->
625 case ident of
626 (NodeIdentifier nid) -> traceEvent t (MxNodeDied nid reason)
627 (ProcessIdentifier pid) -> traceEvent t (MxProcessDied pid reason)
628 _ -> return ()
630traceEventFmtIO :: LocalNode
631 -> String
632 -> [TraceArg]
633 -> IO ()
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--------------------------------------------------------------------------------
647-- [Unified: Table 7]
648nodeController :: NC ()
649nodeController = do
650 node <- ask
651 forever' $ do
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
658 (ctrlMsgSender msg)
659 (NodeIdentifier nid')
660 WithImplicitReconnect
661 msg
662 _ ->
663 return ()
665 case msg of
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 ->
695 liftIO $ do
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
701 unexpected ->
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
708 -> NC ()
709ncEffectMonitor from them mRef = do
710 node <- ask
711 shouldLink <-
712 if not (isLocal node them)
713 then return True
714 else isValidLocalIdentifier them
715 case (shouldLink, isLocal node (ProcessIdentifier from)) of
716 (True, _) -> -- [Unified: first rule]
717 case mRef of
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
730 NCMsg
731 { ctrlMsgSender = NodeIdentifier (localNodeId node)
732 , ctrlMsgSignal = Died them DiedUnknownId
733 }
735-- [Unified: Table 11]
736ncEffectUnlink :: ProcessId -> Identifier -> NC ()
737ncEffectUnlink from them = do
738 node <- ask
739 when (isLocal node (ProcessIdentifier from)) $
740 case them of
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
752 node <- ask
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
760 node <- ask
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) ->
770 forM_ uss $ \us ->
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
786 True ->
787 do forM_ nidlist $ \(nid,_) ->
788 when (not $ isLocal node (NodeIdentifier nid))
789 (forwardNameDeath node nid)
790 return Nothing
791 False -> return $ Just (pid,nidlist) )
792 modify' $ registeredOnNodes ^= (Map.fromList (catMaybes remaining))
793 where
794 forwardNameDeath node nid =
795 liftIO $ sendBinary node
796 (NodeIdentifier $ localNodeId node)
797 (NodeIdentifier $ nid)
798 WithImplicitReconnect
799 NCMsg
800 { ctrlMsgSender = NodeIdentifier (localNodeId node)
801 , ctrlMsgSignal = Died ident reason
802 }
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
810 -- TODO:
811 let proc = case mProc of
812 Left err -> fail $ "Error: Could not resolve closure: " ++ err
813 Right p -> p
814 node <- ask
815 pid' <- liftIO $ forkProcess node proc
816 liftIO $ sendMessage node
817 (NodeIdentifier (localNodeId node))
818 (ProcessIdentifier pid)
819 WithImplicitReconnect
820 (DidSpawn ref pid')
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
827 node <- ask
828 currentVal <- gets (^. registeredHereFor label)
829 isOk <-
830 case mPid of
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
841 case mPid of
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)
849 else let operation =
850 case reregistration of
851 True -> flip decList
852 False -> flip incList
853 in case mPid of
854 Nothing -> return ()
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
872 decList [] _ = []
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)
880 (NodeIdentifier to)
881 WithImplicitReconnect
882 NCMsg
883 { ctrlMsgSender = ProcessIdentifier from
884 , ctrlMsgSignal = reg
885 }
888-- Unified semantics does not explicitly describe 'whereis'
889ncEffectWhereIs :: ProcessId -> String -> NC ()
890ncEffectWhereIs from label = do
891 node <- ask
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
906-- [Issue #DP-20]
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)
913-- [Issue #DP-20]
914ncEffectLocalPortSend :: SendPortId -> Message -> NC ()
915ncEffectLocalPortSend from msg = do
916 node <- ask
917 let pid = sendPortProcessId from
918 cid = sendPortLocalId from
919 liftIO $ withLocalProc node pid $ \proc -> do
920 mChan <- withMVar (processState proc) $ return . (^. typedChannelWithId cid)
921 case mChan of
922 -- in the unlikely event we know nothing about this channel id,
923 -- there's little to be done - perhaps some logging/tracing though...
924 Nothing -> return ()
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"
937-- [Issue #69]
938ncEffectKill :: ProcessId -> ProcessId -> String -> NC ()
939ncEffectKill from to reason = do
940 node <- ask
941 when (isLocal node (ProcessIdentifier to)) $
942 throwException to $ ProcessKillException from reason
944-- [Issue #69]
945ncEffectExit :: ProcessId -> ProcessId -> Message -> NC ()
946ncEffectExit from to reason = do
947 node <- ask
948 when (isLocal node (ProcessIdentifier to)) $
949 throwException to $ ProcessExitException from reason
951-- [Issue #89]
952ncEffectGetInfo :: ProcessId -> ProcessId -> NC ()
953ncEffectGetInfo from pid =
954 let lpid = processLocalId pid
955 them = (ProcessIdentifier pid)
956 in do
957 node <- ask
958 mProc <- liftIO $
959 withMVar (localState node) $ return . (^. localProcessWithId lpid)
960 case mProc of
961 Nothing -> dispatch (isLocal node (ProcessIdentifier from))
962 from node (ProcessInfoNone DiedUnknownId)
963 Just _ -> do
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))
970 from
971 node
972 ProcessInfo {
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
979 }
980 where dispatch :: (Serializable a, Show a)
981 => Bool
982 -> ProcessId
983 -> LocalNode
984 -> a
985 -> NC ()
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
992 pInfo
994 registeredNames = Map.foldlWithKey (\ks k v -> if v == pid
995 then (k:ks)
996 else ks) []
998ncEffectGetNodeStats :: ProcessId -> NodeId -> NC ()
999ncEffectGetNodeStats from _nid = do
1000 node <- ask
1001 ncState <- StateT.get
1002 nodeState <- liftIO $ readMVar (localState node)
1003 let localProcesses' = nodeState ^. localProcesses
1004 stats =
1005 NodeStats {
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--------------------------------------------------------------------------------
1014-- Auxiliary --
1015--------------------------------------------------------------------------------
1017notifyDied :: ProcessId -- ^ Who to notify?
1018 -> Identifier -- ^ Who died?
1019 -> DiedReason -- ^ How did they die?
1020 -> Maybe MonitorRef -- ^ 'Nothing' for linking
1021 -> NC ()
1022notifyDied dest src reason mRef = do
1023 node <- ask
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
1037 (False, _, _) ->
1038 -- The change in sender comes from [Unified: Table 10]
1039 liftIO $ sendBinary node
1040 (NodeIdentifier $ localNodeId node)
1041 (NodeIdentifier $ processNodeId dest)
1042 WithImplicitReconnect
1043 NCMsg
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
1083 node <- ask
1084 liftIO . withMVar (localState node) $ \nSt ->
1085 case ident of
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)
1094 case mProc of
1095 Nothing -> return False
1096 Just proc -> withMVar (processState proc) $ \pSt -> do
1097 let mCh = pSt ^. typedChannelWithId (sendPortLocalId cid)
1098 return $ isJust mCh
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
1109 node <- ask
1110 liftIO $ withLocalProc node pid $ \p -> enqueue (processQueue p) msg
1112throwException :: Exception e => ProcessId -> e -> NC ()
1113throwException pid e = do
1114 node <- ask
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)
1123 forM_ mProc p
1125--------------------------------------------------------------------------------
1126-- Accessors --
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
1155-- should not.
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
1167-- include
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
1174 -> Map Identifier a
1175 -> (Map Identifier a, Map Identifier a)
1176splitNotif ident = Map.partitionWithKey (\k !_v -> ident `impliesDeathOf` k)
1178--------------------------------------------------------------------------------
1179-- Auxiliary --
1180--------------------------------------------------------------------------------
1182-- | Modify and evaluate the state
1183modify' :: MonadState s m => (s -> s) -> m ()
1184modify' f = StateT.get >>= \s -> StateT.put $! f s