1-- | Cloud Haskell primitives
3-- We define these in a separate module so that we don't have to rely on
4-- the closure combinators
5module Control.Distributed.Process.Internal.Primitives
15 -- * Advanced messaging
31 -- * Process management
33 , ProcessTerminationException(..)
39 -- keep the exception constructor hidden, so that handling exit
40 -- reasons /must/ take place via the 'catchExit' family of primitives
41 , ProcessExitException()
46 -- * Monitoring and linking
61 , reregisterRemoteAsync
62 , unregisterRemoteAsync
68 -- * Exception handling
91 -- * Tracing/Debugging
95#if ! MIN_VERSION_base(4,6,0)
96import Prelude hiding (catch)
99import Data.Binary (decode)
100import Data.Time.Clock (getCurrentTime)
101import Data.Time.Format (formatTime)
102import System.Locale (defaultTimeLocale)
103import System.Timeout (timeout)
104import Control.Monad (when)
105import Control.Monad.Reader (ask)
106import Control.Monad.IO.Class (MonadIO, liftIO)
107import Control.Applicative ((<$>))
108import Control.Exception (Exception(..), throw, throwIO, SomeException)
109import qualified Control.Exception as Ex (catch, mask, try)
110import Control.Distributed.Process.Internal.StrictMVar
115import Control.Concurrent.Chan (writeChan)
116import Control.Concurrent.STM
125import Control.Distributed.Process.Internal.CQueue
130import Control.Distributed.Process.Serializable (Serializable, fingerprint)
131import Data.Accessor ((^.), (^:), (^=))
132import Control.Distributed.Static (Closure, Static)
133import Data.Rank1Typeable (Typeable)
134import qualified Control.Distributed.Static as Static (unstatic, unclosure)
135import Control.Distributed.Process.Internal.Types
155 , ProcessExitException(..)
157 , DidUnlinkProcess(..)
162 , ProcessRegistrationException(..)
164 , ProcessInfoNone(..)
166 , createUnencodedMessage
168 , ImplicitReconnect(WithImplicitReconnect, NoImplicitReconnect)
173import Control.Distributed.Process.Internal.Messaging
179import qualified Control.Distributed.Process.Internal.Trace as Trace
180import Control.Distributed.Process.Internal.WeakTQueue
187--------------------------------------------------------------------------------
189--------------------------------------------------------------------------------
192send :: Serializable a => ProcessId -> a -> Process ()
193-- This requires a lookup on every send. If we want to avoid that we need to
194-- modify serializable to allow for stateful (IO) deserialization
197 let node = localNodeId (processNode proc)
198 destNode = (processNodeId them) in do
199 case destNode == node of
200 True -> sendLocal them msg
201 False -> liftIO $ sendMessage (processNode proc)
202 (ProcessIdentifier (processId proc))
203 (ProcessIdentifier them)
207-- | Wait for a message of a specific type
208expect :: forall a. Serializable a => Process a
209expect = receiveWait [match return]
211--------------------------------------------------------------------------------
213--------------------------------------------------------------------------------
215-- | Create a new typed channel
216newChan :: Serializable a => Process (SendPort a, ReceivePort a)
219 liftIO . modifyMVar (processState proc) $ \st -> do
220 let lcid = st ^. channelCounter
221 let cid = SendPortId { sendPortProcessId = processId proc
222 , sendPortLocalId = lcid
224 let sport = SendPort cid
225 chan <- liftIO newTQueueIO
226 chan' <- mkWeakTQueue chan $ finalizer (processState proc) lcid
227 let rport = ReceivePort $ readTQueue chan
228 let tch = TypedChannel chan'
229 return ( (channelCounter ^: (+ 1))
230 . (typedChannelWithId lcid ^= Just tch)
235 finalizer :: StrictMVar LocalProcessState -> LocalSendPortId -> IO ()
236 finalizer st lcid = modifyMVar_ st $
237 return . (typedChannelWithId lcid ^= Nothing)
239-- | Send a message on a typed channel
240sendChan :: Serializable a => SendPort a -> a -> Process ()
241sendChan (SendPort cid) msg = do
243 let node = localNodeId (processNode proc)
244 destNode = processNodeId (sendPortProcessId cid) in do
245 case destNode == node of
246 True -> sendChanLocal cid msg
248 liftIO $ sendBinary (processNode proc)
249 (ProcessIdentifier (processId proc))
250 (SendPortIdentifier cid)
254-- | Wait for a message on a typed channel
255receiveChan :: Serializable a => ReceivePort a -> Process a
256receiveChan = liftIO . atomically . receiveSTM
258-- | Like 'receiveChan' but with a timeout. If the timeout is 0, do a
259-- non-blocking check for a message.
260receiveChanTimeout :: Serializable a => Int -> ReceivePort a -> Process (Maybe a)
261receiveChanTimeout 0 ch = liftIO . atomically $
262 (Just <$> receiveSTM ch) `orElse` return Nothing
263receiveChanTimeout n ch = liftIO . timeout n . atomically $
266-- | Merge a list of typed channels.
268-- The result port is left-biased: if there are messages available on more
269-- than one port, the first available message is returned.
270mergePortsBiased :: Serializable a => [ReceivePort a] -> Process (ReceivePort a)
271mergePortsBiased = return . ReceivePort. foldr1 orElse . map receiveSTM
273-- | Like 'mergePortsBiased', but with a round-robin scheduler (rather than
275mergePortsRR :: Serializable a => [ReceivePort a] -> Process (ReceivePort a)
276mergePortsRR = \ps -> do
277 psVar <- liftIO . atomically $ newTVar (map receiveSTM ps)
278 return $ ReceivePort (rr psVar)
282 rotate (x:xs) = xs ++ [x]
284 rr :: TVar [STM a] -> STM a
287 a <- foldr1 orElse ps
288 writeTVar psVar (rotate ps)
291--------------------------------------------------------------------------------
292-- Advanced messaging --
293--------------------------------------------------------------------------------
295-- | Opaque type used in 'receiveWait' and 'receiveTimeout'
296newtype Match b = Match { unMatch :: MatchOn Message (Process b) }
298-- | Test the matches in order against each message in the queue
299receiveWait :: [Match b] -> Process b
301 queue <- processQueue <$> ask
302 Just proc <- liftIO $ dequeue queue Blocking (map unMatch ms)
305-- | Like 'receiveWait' but with a timeout.
307-- If the timeout is zero do a non-blocking check for matching messages. A
308-- non-zero timeout is applied only when waiting for incoming messages (that is,
309-- /after/ we have checked the messages that are already in the mailbox).
310receiveTimeout :: Int -> [Match b] -> Process (Maybe b)
311receiveTimeout t ms = do
312 queue <- processQueue <$> ask
313 let blockSpec = if t == 0 then NonBlocking else Timeout t
314 mProc <- liftIO $ dequeue queue blockSpec (map unMatch ms)
316 Nothing -> return Nothing
317 Just proc -> Just <$> proc
319matchChan :: ReceivePort a -> (a -> Process b) -> Match b
320matchChan p fn = Match $ MatchChan (fmap fn (receiveSTM p))
322-- | Match against any message of the right type
323match :: forall a b. Serializable a => (a -> Process b) -> Match b
324match = matchIf (const True)
326-- | Match against any message of the right type that satisfies a predicate
327matchIf :: forall a b. Serializable a => (a -> Bool) -> (a -> Process b) -> Match b
328matchIf c p = Match $ MatchMsg $ \msg ->
329 case messageFingerprint msg == fingerprint (undefined :: a) of
332 (UnencodedMessage _ m) ->
333 let m' = unsafeCoerce m :: a in
337 (EncodedMessage _ _) ->
338 if (c decoded) then Just (p decoded) else Nothing
341 -- Make sure the value is fully decoded so that we don't hang to
342 -- bytestrings when the process calling 'matchIf' doesn't process
343 -- the values immediately
344 !decoded = decode (messageEncoding msg)
346-- | Match against any message, regardless of the underlying (contained) type
347matchMessage :: (Message -> Process Message) -> Match Message
348matchMessage p = Match $ MatchMsg $ \msg -> Just (p msg)
350-- | Match against any message (regardless of underlying type) that satisfies a predicate
351matchMessageIf :: (Message -> Bool) -> (Message -> Process Message) -> Match Message
352matchMessageIf c p = Match $ MatchMsg $ \msg ->
357-- | Forward a raw 'Message' to the given 'ProcessId'.
358forward :: Message -> ProcessId -> Process ()
361 let node = localNodeId (processNode proc)
362 destNode = (processNodeId them) in do
363 case destNode == node of
364 True -> sendCtrlMsg Nothing (LocalSend them msg)
365 False -> liftIO $ sendPayload (processNode proc)
366 (ProcessIdentifier (processId proc))
367 (ProcessIdentifier them)
369 (messageToPayload msg)
372-- | Wrap a 'Serializable' value in a 'Message'. Note that 'Message's are
373-- 'Serializable' - like the datum they contain - but remember that deserializing
374-- a 'Message' will yield a 'Message', not the type within it! To obtain the
375-- wrapped datum, use 'unwrapMessage' or 'handleMessage' with a specific type.
380-- send self (wrapMessage "blah")
381-- Nothing <- expectTimeout 1000000 :: Process (Maybe String)
382-- (Just m) <- expectTimeout 1000000 :: Process (Maybe Message)
383-- (Just "blah") <- unwrapMessage m :: Process (Maybe String)
386wrapMessage :: Serializable a => a -> Message
387wrapMessage = createMessage
389-- | Attempt to unwrap a raw 'Message'.
390-- If the type of the decoded message payload matches the expected type, the
391-- value will be returned with @Just@, otherwise @Nothing@ indicates the types
394-- This expression, for example, will evaluate to @Nothing@
395-- > unwrapMessage (wrapMessage "foobar") :: Process (Maybe Int)
397-- Whereas this expression, will yield @Just "foo"@
398-- > unwrapMessage (wrapMessage "foo") :: Process (Maybe String)
400unwrapMessage :: forall a. Serializable a => Message -> Process (Maybe a)
402 case messageFingerprint msg == fingerprint (undefined :: a) of
403 False -> return Nothing
405 (UnencodedMessage _ m) ->
406 let m' = unsafeCoerce m :: a
408 (EncodedMessage _ _) ->
409 return (Just (decoded))
411 decoded :: a -- note [decoding]
412 !decoded = decode (messageEncoding msg)
414-- | Attempt to handle a raw 'Message'.
415-- If the type of the message matches the type of the first argument to
416-- the supplied expression, then the message will be decoded and the expression
417-- evaluated against its value. If this runtime type checking fails however,
418-- @Nothing@ will be returned to indicate the fact. If the check succeeds and
419-- evaluation proceeds, the resulting value with be wrapped with @Just@.
421-- Intended for use in `catchesExit` and `matchAny` primitives.
423handleMessage :: forall a b. (Serializable a)
424 => Message -> (a -> Process b) -> Process (Maybe b)
425handleMessage msg proc = do
426 case messageFingerprint msg == fingerprint (undefined :: a) of
427 False -> return Nothing
429 (UnencodedMessage _ m) ->
430 let m' = unsafeCoerce m :: a -- note [decoding]
431 in do { r <- proc m'; return (Just r) }
432 (EncodedMessage _ _) ->
433 do { r <- proc (decoded :: a); return (Just r) }
435 decoded :: a -- note [decoding]
436 !decoded = decode (messageEncoding msg)
438-- | Match against an arbitrary message. 'matchAny' removes the first available
439-- message from the process mailbox. To handle arbitrary /raw/ messages once
440-- removed from the mailbox, see 'handleMessage' and 'unwrapMessage'.
442matchAny :: forall b. (Message -> Process b) -> Match b
443matchAny p = Match $ MatchMsg $ \msg -> Just (p msg)
445-- | Match against an arbitrary message. Intended for use with 'handleMessage'
446-- and 'unwrapMessage', this function /only/ removes a message from the process
447-- mailbox, /if/ the supplied condition matches. The success (or failure) of
448-- runtime type checks deferred to @handleMessage@ and friends is irrelevant
449-- here, i.e., if the condition evaluates to @True@ then the message will
450-- be removed from the process mailbox and decoded, but that does /not/
451-- guarantee that an expression passed to @handleMessage@ will pass the
452-- runtime type checks and therefore be evaluated.
454matchAnyIf :: forall a b. (Serializable a)
456 -> (Message -> Process b)
458matchAnyIf c p = Match $ MatchMsg $ \msg ->
459 case messageFingerprint msg == fingerprint (undefined :: a) of
460 True | check -> Just (p msg)
465 (EncodedMessage _ _) -> c decoded
466 (UnencodedMessage _ m') -> c (unsafeCoerce m')
468 decoded :: a -- note [decoding]
469 !decoded = decode (messageEncoding msg)
473For an EncodedMessage, we need to ensure the value is fully decoded so that
474we don't hang to bytestrings if the calling process doesn't evaluate
475immediately. For UnencodedMessage we know (because the fingerprint comparison
476succeeds) that unsafeCoerce will not fail.
479-- | Remove any message from the queue
480matchUnknown :: Process b -> Match b
481matchUnknown p = Match $ MatchMsg (const (Just p))
483--------------------------------------------------------------------------------
484-- Process management --
485--------------------------------------------------------------------------------
487-- | Thrown by 'terminate'
488data ProcessTerminationException = ProcessTerminationException
489 deriving (Show, Typeable)
491instance Exception ProcessTerminationException
493-- | Terminate immediately (throws a ProcessTerminationException)
494terminate :: Process a
495terminate = liftIO $ throwIO ProcessTerminationException
498-- | Die immediately - throws a 'ProcessExitException' with the given @reason@.
499die :: Serializable a => a -> Process b
502 liftIO $ throwIO (ProcessExitException pid (createMessage reason))
504-- | Forceful request to kill a process. Where 'exit' provides an exception
505-- that can be caught and handled, 'kill' throws an unexposed exception type
506-- which cannot be handled explicitly (by type).
507kill :: ProcessId -> String -> Process ()
508-- NOTE: We send the message to our local node controller, which will then
509-- forward it to a remote node controller (if applicable). Sending it directly
510-- to a remote node controller means that that the message may overtake a
511-- 'monitor' or 'link' request.
512kill them reason = sendCtrlMsg Nothing (Kill them reason)
514-- | Graceful request to exit a process. Throws 'ProcessExitException' with the
515-- supplied @reason@ encoded as a message. Any /exit signal/ raised in this
516-- manner can be handled using the 'catchExit' family of functions.
517exit :: Serializable a => ProcessId -> a -> Process ()
518-- NOTE: We send the message to our local node controller, which will then
519-- forward it to a remote node controller (if applicable). Sending it directly
520-- to a remote node controller means that that the message may overtake a
521-- 'monitor' or 'link' request.
522exit them reason = sendCtrlMsg Nothing (Exit them (createMessage reason))
524-- | Catches 'ProcessExitException'. The handler will not be applied unless its
525-- type matches the encoded data stored in the exception (see the /reason/
526-- argument given to the 'exit' primitive). If the handler cannot be applied,
527-- the exception will be re-thrown.
529-- To handle 'ProcessExitException' without regard for /reason/, see 'catch'.
530-- To handle multiple /reasons/ of differing types, see 'catchesExit'.
531catchExit :: forall a b . (Show a, Serializable a)
533 -> (ProcessId -> a -> Process b)
535catchExit act exitHandler = catch act handleExit
537 handleExit ex@(ProcessExitException from msg) =
538 if messageFingerprint msg == fingerprint (undefined :: a)
539 then exitHandler from decoded
540 else liftIO $ throwIO ex
543 -- Make sure the value is fully decoded so that we don't hang to
544 -- bytestrings if the caller doesn't use the value immediately
545 !decoded = decode (messageEncoding msg)
547-- | Lift 'Control.Exception.catches' (almost).
549-- As 'ProcessExitException' stores the exit @reason@ as a typed, encoded
550-- message, a handler must accept an input of the expected type. In order to
551-- handle a list of potentially different handlers (and therefore input types),
552-- a handler passed to 'catchesExit' must accept 'AbstractMessage' and return
553-- @Maybe@ (i.e., @Just p@ if it handled the exit reason, otherwise @Nothing@).
555-- See 'maybeHandleMessage' and 'AsbtractMessage' for more details.
556catchesExit :: Process b
557 -> [(ProcessId -> Message -> (Process (Maybe b)))]
559catchesExit act handlers = catch act ((flip handleExit) handlers)
561 handleExit :: ProcessExitException
562 -> [(ProcessId -> Message -> Process (Maybe b))]
564 handleExit ex [] = liftIO $ throwIO ex
565 handleExit ex@(ProcessExitException from msg) (h:hs) = do
568 Nothing -> handleExit ex hs
571-- | Our own process ID
572getSelfPid :: Process ProcessId
573getSelfPid = processId <$> ask
575-- | Get the node ID of our local node
576getSelfNode :: Process NodeId
577getSelfNode = localNodeId . processNode <$> ask
579-- | Get information about the specified process
580getProcessInfo :: ProcessId -> Process (Maybe ProcessInfo)
582 let them = processNodeId pid in do
584 dest <- mkNode them us
585 sendCtrlMsg dest $ GetInfo pid
587 match (\(p :: ProcessInfo) -> return $ Just p)
588 , match (\(_ :: ProcessInfoNone) -> return Nothing)
590 where mkNode :: NodeId -> NodeId -> Process (Maybe NodeId)
591 mkNode them us = case them == us of
592 True -> return Nothing
593 _ -> return $ Just them
595--------------------------------------------------------------------------------
596-- Monitoring and linking --
597--------------------------------------------------------------------------------
599-- | Link to a remote process (asynchronous)
601-- When process A links to process B (that is, process A calls
602-- @link pidB@) then an asynchronous exception will be thrown to process A
603-- when process B terminates (normally or abnormally), or when process A gets
604-- disconnected from process B. Although it is /technically/ possible to catch
605-- these exceptions, chances are if you find yourself trying to do so you should
606-- probably be using 'monitor' rather than 'link'. In particular, code such as
608-- > link pidB -- Link to process B
609-- > expect -- Wait for a message from process B
610-- > unlink pidB -- Unlink again
612-- doesn't quite do what one might expect: if process B sends a message to
613-- process A, and /subsequently terminates/, then process A might or might not
614-- be terminated too, depending on whether the exception is thrown before or
615-- after the 'unlink' (i.e., this code has a race condition).
617-- Linking is all-or-nothing: A is either linked to B, or it's not. A second
618-- call to 'link' has no effect.
620-- Note that 'link' provides unidirectional linking (see 'spawnSupervised').
621-- Linking makes no distinction between normal and abnormal termination of
622-- the remote process.
623link :: ProcessId -> Process ()
624link = sendCtrlMsg Nothing . Link . ProcessIdentifier
626-- | Monitor another process (asynchronous)
628-- When process A monitors process B (that is, process A calls
629-- @monitor pidB@) then process A will receive a 'ProcessMonitorNotification'
630-- when process B terminates (normally or abnormally), or when process A gets
631-- disconnected from process B. You receive this message like any other (using
632-- 'expect'); the notification includes a reason ('DiedNormal', 'DiedException',
633-- 'DiedDisconnect', etc.).
635-- Every call to 'monitor' returns a new monitor reference 'MonitorRef'; if
636-- multiple monitors are set up, multiple notifications will be delivered
637-- and monitors can be disabled individually using 'unmonitor'.
638monitor :: ProcessId -> Process MonitorRef
639monitor = monitor' . ProcessIdentifier
641-- | Establishes temporary monitoring of another process.
643-- @withMonitor pid code@ sets up monitoring of @pid@ for the duration
644-- of @code@. Note: although monitoring is no longer active when
645-- @withMonitor@ returns, there might still be unreceived monitor
646-- messages in the queue.
648withMonitor :: ProcessId -> Process a -> Process a
649withMonitor pid code = bracket (monitor pid) unmonitor (\_ -> code)
650 -- unmonitor blocks waiting for the response, so there's a possibility
651 -- that an exception might interrupt withMonitor before the unmonitor
652 -- has completed. I think that's better than making the unmonitor
657-- This is synchronous in the sense that once it returns you are guaranteed
658-- that no exception will be raised if the remote process dies. However, it is
659-- asynchronous in the sense that we do not wait for a response from the remote
661unlink :: ProcessId -> Process ()
664 receiveWait [ matchIf (\(DidUnlinkProcess pid') -> pid' == pid)
668-- | Remove a node link
670-- This has the same synchronous/asynchronous nature as 'unlink'.
671unlinkNode :: NodeId -> Process ()
674 receiveWait [ matchIf (\(DidUnlinkNode nid') -> nid' == nid)
678-- | Remove a channel (send port) link
680-- This has the same synchronous/asynchronous nature as 'unlink'.
681unlinkPort :: SendPort a -> Process ()
683 unlinkPortAsync sport
684 receiveWait [ matchIf (\(DidUnlinkPort cid) -> cid == sendPortId sport)
690-- This has the same synchronous/asynchronous nature as 'unlink'.
691unmonitor :: MonitorRef -> Process ()
694 receiveWait [ matchIf (\(DidUnmonitor ref') -> ref' == ref)
698--------------------------------------------------------------------------------
699-- Exception handling --
700--------------------------------------------------------------------------------
702-- | Lift 'Control.Exception.catch'
703catch :: Exception e => Process a -> (e -> Process a) -> Process a
706 liftIO $ Ex.catch (runLocalProcess lproc p) (runLocalProcess lproc . h)
708-- | Lift 'Control.Exception.try'
709try :: Exception e => Process a -> Process (Either e a)
712 liftIO $ Ex.try (runLocalProcess lproc p)
714-- | Lift 'Control.Exception.mask'
715mask :: ((forall a. Process a -> Process a) -> Process b) -> Process b
718 liftIO $ Ex.mask $ \restore ->
719 runLocalProcess lproc (p (liftRestore lproc restore))
721 liftRestore :: LocalProcess -> (forall a. IO a -> IO a) -> (forall a. Process a -> Process a)
722 liftRestore lproc restoreIO = liftIO . restoreIO . runLocalProcess lproc
724-- | Lift 'Control.Exception.onException'
725onException :: Process a -> Process b -> Process a
726onException p what = p `catch` \e -> do _ <- what
727 liftIO $ throwIO (e :: SomeException)
729-- | Lift 'Control.Exception.bracket'
730bracket :: Process a -> (a -> Process b) -> (a -> Process c) -> Process c
731bracket before after thing =
732 mask $ \restore -> do
734 r <- restore (thing a) `onException` after a
738-- | Lift 'Control.Exception.bracket_'
739bracket_ :: Process a -> Process b -> Process c -> Process c
740bracket_ before after thing = bracket before (const after) (const thing)
742-- | Lift 'Control.Exception.finally'
743finally :: Process a -> Process b -> Process a
744finally a sequel = bracket_ (return ()) sequel a
746-- | You need this when using 'catches'
747data Handler a = forall e . Exception e => Handler (e -> Process a)
749instance Functor Handler where
750 fmap f (Handler h) = Handler (fmap f . h)
752-- | Lift 'Control.Exception.catches'
753catches :: Process a -> [Handler a] -> Process a
754catches proc handlers = proc `catch` catchesHandler handlers
756catchesHandler :: [Handler a] -> SomeException -> Process a
757catchesHandler handlers e = foldr tryHandler (throw e) handlers
758 where tryHandler (Handler handler) res
759 = case fromException e of
760 Just e' -> handler e'
763--------------------------------------------------------------------------------
765--------------------------------------------------------------------------------
767-- | Like 'expect' but with a timeout
768expectTimeout :: forall a. Serializable a => Int -> Process (Maybe a)
769expectTimeout n = receiveTimeout n [match return]
771-- | Asynchronous version of 'spawn'
773-- ('spawn' is defined in terms of 'spawnAsync' and 'expect')
774spawnAsync :: NodeId -> Closure (Process ()) -> Process SpawnRef
775spawnAsync nid proc = do
776 spawnRef <- getSpawnRef
777 sendCtrlMsg (Just nid) $ Spawn proc spawnRef
780-- | Monitor a node (asynchronous)
781monitorNode :: NodeId -> Process MonitorRef
783 monitor' . NodeIdentifier
785-- | Monitor a typed channel (asynchronous)
786monitorPort :: forall a. Serializable a => SendPort a -> Process MonitorRef
787monitorPort (SendPort cid) =
788 monitor' (SendPortIdentifier cid)
790-- | Remove a monitor (asynchronous)
791unmonitorAsync :: MonitorRef -> Process ()
793 sendCtrlMsg Nothing . Unmonitor
795-- | Link to a node (asynchronous)
796linkNode :: NodeId -> Process ()
797linkNode = link' . NodeIdentifier
799-- | Link to a channel (asynchronous)
800linkPort :: SendPort a -> Process ()
801linkPort (SendPort cid) =
802 link' (SendPortIdentifier cid)
804-- | Remove a process link (asynchronous)
805unlinkAsync :: ProcessId -> Process ()
807 sendCtrlMsg Nothing . Unlink . ProcessIdentifier
809-- | Remove a node link (asynchronous)
810unlinkNodeAsync :: NodeId -> Process ()
812 sendCtrlMsg Nothing . Unlink . NodeIdentifier
814-- | Remove a channel (send port) link (asynchronous)
815unlinkPortAsync :: SendPort a -> Process ()
816unlinkPortAsync (SendPort cid) =
817 sendCtrlMsg Nothing . Unlink $ SendPortIdentifier cid
819--------------------------------------------------------------------------------
821--------------------------------------------------------------------------------
825-- @say message@ sends a message (time, pid of the current process, message)
826-- to the process registered as 'logger'. By default, this process simply
827-- sends the string to 'stderr'. Individual Cloud Haskell backends might
828-- replace this with a different logger process, however.
829say :: String -> Process ()
831 now <- liftIO getCurrentTime
833 nsend "logger" (formatTime defaultTimeLocale "%c" now, us, string)
835--------------------------------------------------------------------------------
837--------------------------------------------------------------------------------
839-- | Register a process with the local registry (asynchronous).
840-- This version will wait until a response is gotten from the
841-- management process. The name must not already be registered.
842-- The process need not be on this node.
843-- A bad registration will result in a 'ProcessRegistrationException'
845-- The process to be registered does not have to be local itself.
846register :: String -> ProcessId -> Process ()
847register = registerImpl False
849-- | Like 'register', but will replace an existing registration.
850-- The name must already be registered.
851reregister :: String -> ProcessId -> Process ()
852reregister = registerImpl True
854registerImpl :: Bool -> String -> ProcessId -> Process ()
855registerImpl force label pid = do
857 sendCtrlMsg Nothing (Register label mynid (Just pid) force)
858 receiveWait [ matchIf (\(RegisterReply label' _) -> label == label')
859 (\(RegisterReply _ ok) -> handleRegistrationReply label ok)
862-- | Register a process with a remote registry (asynchronous).
864-- The process to be registered does not have to live on the same remote node.
865-- Reply wil come in the form of a 'RegisterReply' message
867-- See comments in 'whereisRemoteAsync'
868registerRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
869registerRemoteAsync nid label pid =
870 sendCtrlMsg (Just nid) (Register label nid (Just pid) False)
872reregisterRemoteAsync :: NodeId -> String -> ProcessId -> Process ()
873reregisterRemoteAsync nid label pid =
874 sendCtrlMsg (Just nid) (Register label nid (Just pid) True)
876-- | Remove a process from the local registry (asynchronous).
877-- This version will wait until a response is gotten from the
878-- management process. The name must already be registered.
879unregister :: String -> Process ()
882 sendCtrlMsg Nothing (Register label mynid Nothing False)
883 receiveWait [ matchIf (\(RegisterReply label' _) -> label == label')
884 (\(RegisterReply _ ok) -> handleRegistrationReply label ok)
887-- | Deal with the result from an attempted registration or unregistration
888-- by throwing an exception if necessary
889handleRegistrationReply :: String -> Bool -> Process ()
890handleRegistrationReply label ok =
892 liftIO $ throwIO $ ProcessRegistrationException label
894-- | Remove a process from a remote registry (asynchronous).
896-- Reply wil come in the form of a 'RegisterReply' message
898-- See comments in 'whereisRemoteAsync'
899unregisterRemoteAsync :: NodeId -> String -> Process ()
900unregisterRemoteAsync nid label =
901 sendCtrlMsg (Just nid) (Register label nid Nothing False)
903-- | Query the local process registry
904whereis :: String -> Process (Maybe ProcessId)
906 sendCtrlMsg Nothing (WhereIs label)
907 receiveWait [ matchIf (\(WhereIsReply label' _) -> label == label')
908 (\(WhereIsReply _ mPid) -> return mPid)
911-- | Query a remote process registry (asynchronous)
913-- Reply will come in the form of a 'WhereIsReply' message.
915-- There is currently no synchronous version of 'whereisRemoteAsync': if
916-- you implement one yourself, be sure to take into account that the remote
917-- node might die or get disconnect before it can respond (i.e. you should
918-- use 'monitorNode' and take appropriate action when you receive a
919-- 'NodeMonitorNotification').
920whereisRemoteAsync :: NodeId -> String -> Process ()
921whereisRemoteAsync nid label =
922 sendCtrlMsg (Just nid) (WhereIs label)
924-- | Named send to a process in the local registry (asynchronous)
925nsend :: Serializable a => String -> a -> Process ()
927 sendCtrlMsg Nothing (NamedSend label (createUnencodedMessage msg))
929-- | Named send to a process in a remote registry (asynchronous)
930nsendRemote :: Serializable a => NodeId -> String -> a -> Process ()
931nsendRemote nid label msg =
932 sendCtrlMsg (Just nid) (NamedSend label (createMessage msg))
934--------------------------------------------------------------------------------
936--------------------------------------------------------------------------------
938-- | Resolve a static value
939unStatic :: Typeable a => Static a -> Process a
941 rtable <- remoteTable . processNode <$> ask
942 case Static.unstatic rtable static of
943 Left err -> fail $ "Could not resolve static value: " ++ err
946-- | Resolve a closure
947unClosure :: Typeable a => Closure a -> Process a
948unClosure closure = do
949 rtable <- remoteTable . processNode <$> ask
950 case Static.unclosure rtable closure of
951 Left err -> fail $ "Could not resolve closure: " ++ err
954--------------------------------------------------------------------------------
956--------------------------------------------------------------------------------
958-- | Cloud Haskell provides the illusion of connection-less, reliable, ordered
959-- message passing. However, when network connections get disrupted this
960-- illusion cannot always be maintained. Once a network connection breaks (even
961-- temporarily) no further communication on that connection will be possible.
962-- For example, if process A sends a message to process B, and A is then
963-- notified (by monitor notification) that it got disconnected from B, A will
964-- not be able to send any further messages to B, /unless/ A explicitly
965-- indicates that it is acceptable to attempt to reconnect to B using the
966-- Cloud Haskell 'reconnect' primitive.
968-- Importantly, when A calls 'reconnect' it acknowledges that some messages to
969-- B might have been lost. For instance, if A sends messages m1 and m2 to B,
970-- then receives a monitor notification that its connection to B has been lost,
971-- calls 'reconnect' and then sends m3, it is possible that B will receive m1
974-- Note that 'reconnect' does not mean /reconnect now/ but rather /it is okay
975-- to attempt to reconnect on the next send/. In particular, if no further
976-- communication attempts are made to B then A can use reconnect to clean up
977-- its connection to B.
978reconnect :: ProcessId -> Process ()
981 node <- processNode <$> ask
982 liftIO $ disconnect node (ProcessIdentifier us) (ProcessIdentifier them)
984-- | Reconnect to a sendport. See 'reconnect' for more information.
985reconnectPort :: SendPort a -> Process ()
986reconnectPort them = do
988 node <- processNode <$> ask
989 liftIO $ disconnect node (ProcessIdentifier us) (SendPortIdentifier (sendPortId them))
991--------------------------------------------------------------------------------
992-- Debugging/Tracing --
993--------------------------------------------------------------------------------
995-- | Send a message to the internal (system) trace facility. If tracing is
996-- enabled, this will create a custom trace event. Note that several Cloud Haskell
997-- sub-systems also generate trace events for informational/debugging purposes,
998-- thus traces generated this way will not be the only output seen.
1000-- Just as with the "Debug.Trace" module, this is a debugging/tracing facility
1001-- for use in development, and should not be used in a production setting -
1002-- which is why the default behaviour is to trace to the GHC eventlog. For a
1003-- general purpose logging facility, you should consider 'say'.
1005-- Trace events can be written to the GHC event log, a text file, or to the
1006-- standard system logger process (see 'say'). The default behaviour for writing
1007-- to the eventlog requires specific intervention to work, without which traces
1008-- are silently dropped/ignored and no output will be generated.
1009-- The GHC eventlog documentation provides information about enabling, viewing
1010-- and working with event traces: <http://hackage.haskell.org/trac/ghc/wiki/EventLog>.
1012-- When a new local node is started, the contents of the environment variable
1013-- @DISTRIBUTED_PROCESS_TRACE_FILE@ are checked for a valid file path. If this
1014-- exists and the file can be opened for writing, all trace output will be directed
1015-- thence. If the environment variable is empty, the path invalid, or the file
1016-- unavailable for writing - e.g., because another node has already started
1017-- tracing to it - then the @DISTRIBUTED_PROCESS_TRACE_CONSOLE@ environment
1018-- variable is checked for /any/ non-empty value. If this is set, then all trace
1019-- output will be directed to the system logger process. If neither evironment
1020-- variable provides a valid trace configuration, all internal traces are written
1021-- to "Debug.Trace.traceEventIO", which writes to the GHC eventlog.
1023-- Users of the /simplelocalnet/ Cloud Haskell backend should also note that
1024-- because the trace file option only supports trace output from a single node
1025-- (so as to avoid interleaving), a file trace configured for the master node will
1026-- prevent slaves from tracing to the file and they will fall back to using the
1027-- console/'say' or eventlog instead.
1029trace :: String -> Process ()
1031 node <- processNode <$> ask
1032 liftIO $ Trace.trace (localTracer node) s
1034--------------------------------------------------------------------------------
1035-- Auxiliary functions --
1036--------------------------------------------------------------------------------
1038sendLocal :: (Serializable a) => ProcessId -> a -> Process ()
1040 sendCtrlMsg Nothing $ LocalSend pid (createUnencodedMessage msg)
1042sendChanLocal :: (Serializable a) => SendPortId -> a -> Process ()
1043sendChanLocal spId msg =
1044 -- we *must* fully serialize/encode the message here, because
1045 -- attempting to use `unsafeCoerce' in the node controller
1046 -- won't work since we know nothing about the required type
1047 sendCtrlMsg Nothing $ LocalPortSend spId (createUnencodedMessage msg)
1049getMonitorRefFor :: Identifier -> Process MonitorRef
1050getMonitorRefFor ident = do
1052 liftIO $ modifyMVar (processState proc) $ \st -> do
1053 let counter = st ^. monitorCounter
1054 return ( monitorCounter ^: (+ 1) $ st
1055 , MonitorRef ident counter
1058getSpawnRef :: Process SpawnRef
1061 liftIO $ modifyMVar (processState proc) $ \st -> do
1062 let counter = st ^. spawnCounter
1063 return ( spawnCounter ^: (+ 1) $ st
1067-- | Monitor a process/node/channel
1068monitor' :: Identifier -> Process MonitorRef
1070 monitorRef <- getMonitorRefFor ident
1071 sendCtrlMsg Nothing $ Monitor monitorRef
1074-- | Link to a process/node/channel
1075link' :: Identifier -> Process ()
1076link' = sendCtrlMsg Nothing . Link
1078-- Send a control message
1079sendCtrlMsg :: Maybe NodeId -- ^ Nothing for the local node
1080 -> ProcessSignal -- ^ Message to send
1082sendCtrlMsg mNid signal = do
1084 let msg = NCMsg { ctrlMsgSender = ProcessIdentifier (processId proc)
1085 , ctrlMsgSignal = signal
1089 liftIO $ writeChan (localCtrlChan (processNode proc)) msg
1091 liftIO $ sendBinary (processNode proc)
1092 (ProcessIdentifier (processId proc))
1093 (NodeIdentifier nid)
1094 WithImplicitReconnect
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