git.iko.soy/distributed-process
on 5eaedc2 help sign in
446 lines 12 kB history raw
1{-# LANGUAGE CPP #-}
2{- | [Cloud Haskell]
4This is an implementation of Cloud Haskell, as described in
5/Towards Haskell in the Cloud/ by Jeff Epstein, Andrew Black, and Simon
6Peyton Jones (see
7<http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/>),
8although some of the details are different. The precise message passing
9semantics are based on /A unified semantics for future Erlang/ by Hans
10Svensson, Lars-Åke Fredlund and Clara Benac Earle.
12For a detailed description of the package and other reference materials,
13please see the distributed-process wiki page on github:
14<https://github.com/haskell-distributed/distributed-process/wiki>.
16-}
17module Control.Distributed.Process
18 ( -- * Basic types
19 ProcessId
20 , NodeId(..)
21 , Process
22 , SendPortId
23 , processNodeId
24 , sendPortProcessId
25 , liftIO -- Reexported for convenience
26 -- * Basic messaging
27 , send
28 , usend
29 , expect
30 , expectTimeout
31 -- * Channels
32 , ReceivePort
33 , SendPort
34 , sendPortId
35 , newChan
36 , sendChan
37 , receiveChan
38 , receiveChanTimeout
39 , mergePortsBiased
40 , mergePortsRR
41 -- * Unsafe messaging variants
42 , unsafeSend
43 , unsafeUSend
44 , unsafeSendChan
45 , unsafeNSend
46 , unsafeNSendRemote
47 , unsafeWrapMessage
48 -- * Advanced messaging
49 , Match
50 , receiveWait
51 , receiveTimeout
52 , match
53 , matchIf
54 , matchUnknown
55 , matchAny
56 , matchAnyIf
57 , matchChan
58 , matchSTM
59 , Message
60 , matchMessage
61 , matchMessageIf
62 , isEncoded
63 , wrapMessage
64 , unwrapMessage
65 , handleMessage
66 , handleMessageIf
67 , handleMessage_
68 , handleMessageIf_
69 , forward
70 , uforward
71 , delegate
72 , relay
73 , proxy
74 -- * Process management
75 , spawn
76 , call
77 , terminate
78 , die
79 , kill
80 , exit
81 , catchExit
82 , catchesExit
83 , ProcessTerminationException(..)
84 , ProcessRegistrationException(..)
85 , SpawnRef
86 , getSelfPid
87 , getSelfNode
88 , ProcessInfo(..)
89 , getProcessInfo
90 , NodeStats(..)
91 , getNodeStats
92 , getLocalNodeStats
93 -- * Monitoring and linking
94 , link
95 , linkNode
96 , linkPort
97 , unlink
98 , unlinkNode
99 , unlinkPort
100 , monitor
101 , monitorNode
102 , monitorPort
103 , unmonitor
104 , withMonitor
105 , MonitorRef -- opaque
106 , ProcessLinkException(..)
107 , NodeLinkException(..)
108 , PortLinkException(..)
109 , ProcessMonitorNotification(..)
110 , NodeMonitorNotification(..)
111 , PortMonitorNotification(..)
112 , DiedReason(..)
113 -- * Closures
114 , Closure
115 , closure
116 , Static
117 , unStatic
118 , unClosure
119 , RemoteTable
120 -- * Logging
121 , say
122 -- * Registry
123 , register
124 , reregister
125 , unregister
126 , whereis
127 , nsend
128 , registerRemoteAsync
129 , reregisterRemoteAsync
130 , unregisterRemoteAsync
131 , whereisRemoteAsync
132 , nsendRemote
133 , WhereIsReply(..)
134 , RegisterReply(..)
135 -- * Exception handling
136 , catch
137 , Handler(..)
138 , catches
139 , try
140 , mask
141 , mask_
142 , onException
143 , bracket
144 , bracket_
145 , finally
146 -- * Auxiliary API
147 , spawnAsync
148 , spawnSupervised
149 , spawnLink
150 , spawnMonitor
151 , spawnChannel
152 , DidSpawn(..)
153 -- * Local versions of 'spawn'
154 , spawnLocal
155 , spawnChannelLocal
156 , callLocal
157 -- * Reconnecting
158 , reconnect
159 , reconnectPort
160 ) where
162import Control.Monad.IO.Class (liftIO)
163import Control.Applicative
164import Control.Monad.Reader (ask)
165import Control.Concurrent (killThread)
166import Control.Concurrent.MVar
167 ( MVar
168 , newEmptyMVar
169 , takeMVar
170 , putMVar
171 )
172import Control.Distributed.Static
173 ( Closure
174 , closure
175 , Static
176 , RemoteTable
177 )
178import Control.Distributed.Process.Internal.Types
179 ( NodeId(..)
180 , ProcessId(..)
181 , Process(..)
182 , MonitorRef(..)
183 , ProcessMonitorNotification(..)
184 , NodeMonitorNotification(..)
185 , PortMonitorNotification(..)
186 , ProcessLinkException(..)
187 , NodeLinkException(..)
188 , PortLinkException(..)
189 , ProcessRegistrationException(..)
190 , DiedReason(..)
191 , SpawnRef(..)
192 , DidSpawn(..)
193 , SendPort(..)
194 , ReceivePort(..)
195 , SendPortId(..)
196 , WhereIsReply(..)
197 , RegisterReply(..)
198 , LocalProcess(processNode)
199 , Message
200 , localProcessWithId
201 )
202import Control.Distributed.Process.Serializable (Serializable)
203import Control.Distributed.Process.Internal.Primitives
204 ( -- Basic messaging
205 send
206 , usend
207 , expect
208 -- Channels
209 , newChan
210 , sendChan
211 , receiveChan
212 , mergePortsBiased
213 , mergePortsRR
214 , unsafeSend
215 , unsafeUSend
216 , unsafeSendChan
217 , unsafeNSend
218 , unsafeNSendRemote
219 -- Advanced messaging
220 , Match
221 , receiveWait
222 , receiveTimeout
223 , match
224 , matchIf
225 , matchUnknown
226 , matchAny
227 , matchAnyIf
228 , matchChan
229 , matchSTM
230 , matchMessage
231 , matchMessageIf
232 , isEncoded
233 , wrapMessage
234 , unsafeWrapMessage
235 , unwrapMessage
236 , handleMessage
237 , handleMessageIf
238 , handleMessage_
239 , handleMessageIf_
240 , forward
241 , uforward
242 , delegate
243 , relay
244 , proxy
245 -- Process management
246 , terminate
247 , ProcessTerminationException(..)
248 , die
249 , exit
250 , catchExit
251 , catchesExit
252 , kill
253 , getSelfPid
254 , getSelfNode
255 , ProcessInfo(..)
256 , getProcessInfo
257 , NodeStats(..)
258 , getNodeStats
259 , getLocalNodeStats
260 -- Monitoring and linking
261 , link
262 , linkNode
263 , linkPort
264 , unlink
265 , unlinkNode
266 , unlinkPort
267 , monitor
268 , monitorNode
269 , monitorPort
270 , unmonitor
271 , withMonitor
272 -- Logging
273 , say
274 -- Registry
275 , register
276 , reregister
277 , unregister
278 , whereis
279 , nsend
280 , registerRemoteAsync
281 , reregisterRemoteAsync
282 , unregisterRemoteAsync
283 , whereisRemoteAsync
284 , nsendRemote
285 -- Closures
286 , unStatic
287 , unClosure
288 -- Exception handling
289 , catch
290 , Handler(..)
291 , catches
292 , try
293 , mask
294 , mask_
295 , onException
296 , bracket
297 , bracket_
298 , finally
299 -- Auxiliary API
300 , expectTimeout
301 , receiveChanTimeout
302 , spawnAsync
303 -- Reconnecting
304 , reconnect
305 , reconnectPort
306 )
307import Control.Distributed.Process.Node (forkProcess)
308import Control.Distributed.Process.Internal.Types
309 ( processThread
310 , withValidLocalState
311 )
312import Control.Distributed.Process.Internal.Spawn
313 ( -- Spawning Processes/Channels
314 spawn
315 , spawnLink
316 , spawnMonitor
317 , spawnChannel
318 , spawnSupervised
319 , call
320 )
321import qualified Control.Monad.Catch as Catch
323#if MIN_VERSION_base(4,6,0)
324import Prelude
325#else
326import Prelude hiding (catch)
327#endif
328import Control.Distributed.Process.Internal.StrictMVar (readMVar)
329import qualified Control.Exception as Exception (onException)
330import Data.Accessor ((^.))
331import Data.Foldable (forM_)
334-- INTERNAL NOTES
335--
336-- 1. 'send' never fails. If you want to know that the remote process received
337-- your message, you will need to send an explicit acknowledgement. If you
338-- want to know when the remote process failed, you will need to monitor
339-- that remote process.
340--
341-- 2. 'send' may block (when the system TCP buffers are full, while we are
342-- trying to establish a connection to the remote endpoint, etc.) but its
343-- return does not imply that the remote process received the message (much
344-- less processed it). When 'send' targets a local process, it is dispatched
345-- via the node controller however, in which cases it will /not/ block. This
346-- isn't part of the semantics, so it should be ok. The ordering is maintained
347-- because the ctrlChannel still has FIFO semantics with regards interactions
348-- between two disparate forkIO threads.
349--
350-- 3. Message delivery is reliable and ordered. That means that if process A
351-- sends messages m1, m2, m3 to process B, B will either arrive all three
352-- messages in order (m1, m2, m3) or a prefix thereof; messages will not be
353-- 'missing' (m1, m3) or reordered (m1, m3, m2)
354--
355-- In order to guarantee (3), we stipulate that
356--
357-- 3a. We do not garbage collect connections because Network.Transport provides
358-- ordering guarantees only *per connection*.
359--
360-- 3b. Once a connection breaks, we have no way of knowing which messages
361-- arrived and which did not; hence, once a connection fails, we assume the
362-- remote process to be forever unreachable. Otherwise we might sent m1 and
363-- m2, get notified of the broken connection, reconnect, send m3, but only
364-- m1 and m3 arrive.
365--
366-- 3c. As a consequence of (3b) we should not reuse PIDs. If a process dies,
367-- we consider it forever unreachable. Hence, new processes should get new
368-- IDs or they too would be considered unreachable.
369--
370-- Main reference for Cloud Haskell is
371--
372-- [1] "Towards Haskell in the Cloud", Jeff Epstein, Andrew Black and Simon
373-- Peyton-Jones.
374-- http://research.microsoft.com/en-us/um/people/simonpj/papers/parallel/remote.pdf
375--
376-- The precise semantics for message passing is based on
377--
378-- [2] "A Unified Semantics for Future Erlang", Hans Svensson, Lars-Ake Fredlund
379-- and Clara Benac Earle (not freely available online, unfortunately)
380--
381-- Some pointers to related documentation about Erlang, for comparison and
382-- inspiration:
383--
384-- [3] "Programming Distributed Erlang Applications: Pitfalls and Recipes",
385-- Hans Svensson and Lars-Ake Fredlund
386-- http://man.lupaworld.com/content/develop/p37-svensson.pdf
387-- [4] The Erlang manual, sections "Message Sending" and "Send"
388-- http://www.erlang.org/doc/reference_manual/processes.html#id82409
389-- http://www.erlang.org/doc/reference_manual/expressions.html#send
390-- [5] Questions "Is the order of message reception guaranteed?" and
391-- "If I send a message, is it guaranteed to reach the receiver?" of
392-- the Erlang FAQ
393-- http://www.erlang.org/faq/academic.html
394-- [6] "Delivery of Messages", post on erlang-questions
395-- http://erlang.org/pipermail/erlang-questions/2012-February/064767.html
397--------------------------------------------------------------------------------
398-- Local versions of spawn --
399--------------------------------------------------------------------------------
401-- | Spawn a process on the local node
402spawnLocal :: Process () -> Process ProcessId
403spawnLocal proc = do
404 node <- processNode <$> ask
405 liftIO $ forkProcess node proc
407-- | Create a new typed channel, spawn a process on the local node, passing it
408-- the receive port, and return the send port
409spawnChannelLocal :: Serializable a
410 => (ReceivePort a -> Process ())
411 -> Process (SendPort a)
412spawnChannelLocal proc = do
413 node <- processNode <$> ask
414 liftIO $ do
415 mvar <- newEmptyMVar
416 _ <- forkProcess node $ do
417 -- It is important that we allocate the new channel in the new process,
418 -- because otherwise it will be associated with the wrong process ID
419 (sport, rport) <- newChan
420 liftIO $ putMVar mvar sport
421 proc rport
422 takeMVar mvar
424-- | Local version of 'call'. Running a process in this way isolates it from
425-- messages sent to the caller process, and also allows silently dropping late
426-- or duplicate messages sent to the isolated process after it exits.
427-- Silently dropping messages may not always be the best approach.
428callLocal :: Process a -> Process a
429callLocal proc = Catch.mask $ \release -> do
430 mv <- liftIO newEmptyMVar :: Process (MVar (Either Catch.SomeException a))
431 child <- spawnLocal $ Catch.try (release proc) >>= liftIO . putMVar mv
432 lproc <- ask
433 liftIO $ do
434 rs <- Exception.onException (takeMVar mv) $ Catch.uninterruptibleMask_ $
435 -- Exceptions need to be prevented from interrupting the clean up or
436 -- the original exception which caused entering the handler could be
437 -- forgotten. For instance, this could have a problematic effect
438 -- when the original exception was meant to kill the thread and the
439 -- second exception doesn't (like the exception thrown by
440 -- 'System.Timeout.timeout').
441 do mchildThreadId <- withValidLocalState (processNode lproc) $
442 \vst -> return $ fmap processThread $
443 vst ^. localProcessWithId (processLocalId child)
444 forM_ mchildThreadId killThread
445 takeMVar mv
446 either Catch.throwM return rs