git.iko.soy/distributed-process
on df911bf help sign in
477 lines 20 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2{-# LANGUAGE DeriveGeneric #-}
3{-# LANGUAGE StandaloneDeriving #-}
4{-# LANGUAGE ExistentialQuantification #-}
5{-# LANGUAGE ScopedTypeVariables #-}
6{-# LANGUAGE RecordWildCards #-}
7{-# LANGUAGE PatternGuards #-}
8{-# LANGUAGE FlexibleInstances #-}
9{-# LANGUAGE UndecidableInstances #-}
11-----------------------------------------------------------------------------
12-- |
13-- Module : Control.Distributed.Process.Management
14-- Copyright : (c) Well-Typed / Tim Watson
15-- License : BSD3 (see the file LICENSE)
16--
17-- Maintainer : Tim Watson <watson.timothy@gmail.com>
18-- Stability : experimental
19-- Portability : non-portable (requires concurrency)
20--
21-- [Management Extensions API]
22--
23-- This module presents an API for creating /Management Agents/:
24-- special processes that are capable of receiving and responding to
25-- a node's internal system events. These /system events/ are delivered by
26-- the management event bus: An internal subsystem maintained for each
27-- running node, to which all agents are automatically subscribed.
28--
29-- /Agents/ are defined in terms of /event sinks/, taking a particular
30-- @Serializable@ type and evaluating to an action in the 'MxAgent' monad in
31-- response. Each 'MxSink' evaluates to an 'MxAction' that specifies whether
32-- the agent should continue processing it's inputs or stop. If the type of a
33-- message cannot be matched to any of the agent's sinks, it will be discarded.
34-- A sink can also deliberately skip processing a message, deferring to the
35-- remaining handlers. This is the /only/ way that more than one event sink
36-- can handle the same data type, since otherwise the first /type match/ will
37-- /win/ every time a message arrives. See 'mxSkip' for details.
38--
39-- Various events are published to the management event bus automatically,
40-- the full list of which can be found in the definition of the 'MxEvent' data
41-- type. Additionally, clients of the /Management API/ can publish arbitrary
42-- @Serializable@ data to the event bus using 'mxNotify'. All running agents
43-- receive all events (from the primary event bus to which they're subscribed).
44--
45-- Agent processes are automatically registered on the local node, and can
46-- receive messages via their mailbox just like ordinary processes. Unlike
47-- ordinary @Process@ code however, it is unnecessary (though possible) for
48-- agents to use the base @expect@ and @receiveX@ primitives to do this, since
49-- the management infrastructure will continuously read from both the primary
50-- event bus /and/ the process' own mailbox. Messages are transparently passed
51-- to the agent's event sinks from both sources, so an agent need only concern
52-- itself with how to respond to its inputs.
53--
54-- Some agents may wish to prioritise messages from their mailbox over traffic
55-- on the management event bus, or vice versa. The 'mxReceive' and
56-- 'mxReceiveChan' API calls do this for the mailbox and event bus,
57-- respectively. The /prioritisation/ these APIs offer is simply that the chosen
58-- data stream will be checked first. No blocking will occur if the chosen
59-- (prioritised) source is devoid of input messages, instead the agent handling
60-- code will revert to switching between the alternatives in /round-robin/ as
61-- usual. If messages exist in one or more channels, they will be consumed as
62-- soon as they're available, priority is effectively a hint about which
63-- channel to consume from, should messages be available in both.
64--
65-- Prioritisation then, is a /hint/ about the preference of data source from
66-- which the next input should be chosen. No guarantee can be made that the
67-- chosen source will in fact be selected at runtime.
68--
69-- [Management API Semantics]
70--
71-- The management API provides /no guarantees whatsoever/, viz:
72--
73-- * The ordering of messages delivered to the event bus.
74--
75-- * The order in which agents will be executed.
76--
77-- * Whether messages will be taken from the mailbox first, or the event bus.
78--
79-- [Management Data API]
80--
81-- Both management agents and clients of the API have access to a variety of
82-- data storage capabilities, to facilitate publishing and consuming useful
83-- system information. Agents maintain their own internal state privately (via a
84-- state transformer - see 'mxGetLocal' et al), however it is possible for
85-- agents to share additional data with each other (and the outside world)
86-- using whatever mechanism the user wishes, e.g., acidstate, or shared memory
87-- primitives.
88--
89-- [Defining Agents]
90--
91-- New agents are defined with 'mxAgent' and require a unique 'MxAgentId', an
92-- initial state - 'MxAgent' runs in a state transformer - and a list of the
93-- agent's event sinks. Each 'MxSink' is defined in terms of a specific
94-- @Serializable@ type, via the 'mxSink' function, binding the event handler
95-- expression to inputs of only that type.
96--
97-- Apart from modifying its own local state, an agent can execute arbitrary
98-- @Process a@ code via lifting (see 'liftMX') and even publish its own messages
99-- back to the primary event bus (see 'mxBroadcast').
100--
101-- Since messages are delivered to agents from both the management event bus and
102-- the agent processes mailbox, agents (i.e., event sinks) will generally have
103-- no idea as to their origin. An agent can, however, choose to prioritise the
104-- choice of input (source) each time one of its event sinks runs. The /standard/
105-- way for an event sink to indicate that the agent is ready for its next input
106-- is to evaluate 'mxReady'. When this happens, the management infrastructure
107-- will obtain data from the event bus and process' mailbox in a round robbin
108-- fashion, i.e., one after the other, changing each time.
109--
110-- [Example Code]
111--
112-- What follows is a grossly over-simplified example of a management agent that
113-- provides a basic name monitoring facility. Whenever a process name is
114-- registered or unregistered, clients are informed of the fact.
115--
116-- > -- simple notification data type
117-- >
118-- > data Registration = Reg { added :: Bool
119-- > , procId :: ProcessId
120-- > , name :: String
121-- > }
122-- >
123-- > -- start a /name monitoring agent/
124-- > nameMonitorAgent = do
125-- > mxAgent (MxAgentId "name-monitor") Set.empty [
126-- > (mxSink $ \(pid :: ProcessId) -> do
127-- > mxUpdateState $ Set.insert pid
128-- > mxReady)
129-- > , (mxSink $
130-- > let act =
131-- > case ev of
132-- > (MxRegistered p n) -> notify True n p
133-- > (MxUnRegistered p n) -> notify False n p
134-- > _ -> return ()
135-- > act >> mxReady)
136-- > ]
137-- > where
138-- > notify a n p = do
139-- > Foldable.mapM_ (liftMX . deliver (Reg a n p)) =<< mxGetLocal
140-- >
141--
142-- The client interface (for sending their pid) can take one of two forms:
143--
144-- > monitorNames = getSelfPid >>= nsend "name-monitor"
145-- > monitorNames2 = getSelfPid >>= mxNotify
146--
147-- For some real-world examples, see the distributed-process-platform package.
148--
149-- [Performance, Stablity and Scalability]
150--
151-- /Management Agents/ offer numerous advantages over regular processes:
152-- broadcast communication with them can have a lower latency, they offer
153-- simplified messgage (i.e., input type) handling and they have access to
154-- internal system information that would be otherwise unobtainable.
155--
156-- Do not be tempted to implement everything (e.g., the kitchen sink) using the
157-- management API though. There are overheads associated with management agents
158-- which is why they're presented as tools for consuming low level system
159-- information, instead of as /application level/ development tools.
160--
161-- Agents that rely heavily on a busy mailbox can cause the management event
162-- bus to backlog un-GC'ed data, leading to increased heap space. Producers that
163-- do not take care to avoid passing unevaluated thunks to the API can crash
164-- /all/ the agents in the system. Agents are not monitored or managed in any
165-- way, and those that crash will not be restarted.
166--
167-- The management event bus can receive a great deal of traffic. Every time
168-- a message is sent and/or received, an event is passed to the agent controller
169-- and broadcast to all agents (plus the trace controller, if tracing is enabled
170-- for the node). This is already a significant overhead - though profiling and
171-- benchmarks have demonstrated that it does not adversely affect performance
172-- if few agents are installed. Agents will typically use more cycles than plain
173-- processes, since they perform additional work: selecting input data from both
174-- the event bus /and/ their own mailboxes, plus searching through the set of
175-- event sinks (for each agent) to determine the right handler for the event.
176--
177-- [Architecture Overview]
178--
179-- The architecture of the management event bus is internal and subject to
180-- change without prior notice. The description that follows is provided for
181-- informational purposes only.
182--
183-- When a node initially starts, two special, internal system processes are
184-- started to support the management infrastructure. The first, known as the
185-- /trace controller/, is responsible for consuming 'MxEvent's and forwarding
186-- them to the configured tracer - see "Control.Distributed.Process.Debug" for
187-- further details. The second is the /management agent controller/, and is the
188-- primary worker process underpinning the management infrastructure. All
189-- published management events are routed to this process, which places them
190-- onto a system wide /event bus/ and additionally passes them directly to the
191-- /trace controller/.
192--
193-- There are several reasons for segregating the tracing and management control
194-- planes in this fashion. Tracing can be enabled or disabled by clients, whilst
195-- the management event bus cannot, since in addition to providing
196-- runtime instrumentation, its intended use-cases include node monitoring, peer
197-- discovery (via topology providing backends) and other essential system
198-- services that require knowledge of otherwise hidden system internals. Tracing
199-- is also subject to /trace flags/ that limit the specific 'MxEvent's delivered
200-- to trace clients - an overhead/complexity not shared by management agents.
201-- Finally, tracing and management agents are implemented using completely
202-- different signalling techniques - more on this later - which would introduce
203-- considerable complexity if the shared the same /event loop/.
204--
205-- The management control plane is driven by a shared broadcast channel, which
206-- is written to by the agent controller and subscribed to by all agent
207-- processes. Agents are spawned as regular processes, whose primary
208-- implementation (i.e., /server loop/) is responsible for consuming
209-- messages from both the broadcast channel and their own mailbox. Once
210-- consumed, messages are applied to the agent's /event sinks/ until one
211-- matches the input, at which point it is applied and the loop continues.
212-- The implementation chooses from the event bus and the mailbox in a
213-- round-robin fashion, until a message is received. This polling activity would
214-- lead to management agents consuming considerable system resources if left
215-- unchecked, therefore the implementation will poll for a limitted number of
216-- retries, after which it will perform a blocking read on the event bus.
217--
218-----------------------------------------------------------------------------
219module Control.Distributed.Process.Management
220 (
221 MxEvent(..)
222 -- * Firing Arbitrary /Mx Events/
223 , mxNotify
224 -- * Constructing Mx Agents
225 , MxAction()
226 , MxAgentId(..)
227 , MxAgent()
228 , mxAgent
229 , mxAgentWithFinalize
230 , MxSink()
231 , mxSink
232 , mxGetId
233 , mxDeactivate
234 , mxReady
235 , mxSkip
236 , mxReceive
237 , mxReceiveChan
238 , mxBroadcast
239 , mxSetLocal
240 , mxGetLocal
241 , mxUpdateLocal
242 , liftMX
243 ) where
245import Control.Applicative
246import Control.Concurrent.STM (atomically)
247import Control.Concurrent.STM.TChan
248 ( readTChan
249 , writeTChan
250 , TChan
251 )
252import Control.Distributed.Process.Internal.Primitives
253 ( receiveWait
254 , matchAny
255 , matchSTM
256 , unwrapMessage
257 , register
258 , whereis
259 , die
260 )
261import Control.Distributed.Process.Internal.Types
262 ( Process
263 , ProcessId
264 , Message
265 , LocalProcess(..)
266 , LocalNode(..)
267 , MxEventBus(..)
268 , unsafeCreateUnencodedMessage
269 )
270import Control.Distributed.Process.Management.Internal.Bus (publishEvent)
271import Control.Distributed.Process.Management.Internal.Types
272 ( MxAgentId(..)
273 , MxAgent(..)
274 , MxAction(..)
275 , ChannelSelector(..)
276 , MxAgentState(..)
277 , MxSink
278 , MxEvent(..)
279 )
280import Control.Distributed.Process.Serializable (Serializable)
281import Control.Monad.IO.Class (liftIO)
282import Control.Monad.Reader (ask)
283import Control.Monad.Catch (onException)
284import qualified Control.Monad.State as ST
285 ( get
286 , modify
287 , lift
288 , runStateT
289 )
290import Prelude
292-- | Publishes an arbitrary @Serializable@ message to the management event bus.
293-- Note that /no attempt is made to force the argument/, therefore it is very
294-- important that you do not pass unevaluated thunks that might crash the
295-- receiving process via this API, since /all/ registered agents will gain
296-- access to the data structure once it is broadcast by the agent controller.
297mxNotify :: (Serializable a) => a -> Process ()
298mxNotify msg = do
299 bus <- localEventBus . processNode <$> ask
300 liftIO $ publishEvent bus $ unsafeCreateUnencodedMessage msg
302--------------------------------------------------------------------------------
303-- API for writing user defined management extensions (i.e., agents) --
304--------------------------------------------------------------------------------
306-- | Return the 'MxAgentId' for the currently executing agent.
307--
308mxGetId :: MxAgent s MxAgentId
309mxGetId = ST.get >>= return . mxAgentId
311-- | The 'MxAgent' version of 'mxNotify'.
312--
313mxBroadcast :: (Serializable m) => m -> MxAgent s ()
314mxBroadcast msg = do
315 state <- ST.get
316 liftMX $ liftIO $ atomically $ do
317 writeTChan (mxBus state) (unsafeCreateUnencodedMessage msg)
319-- | Gracefully terminate an agent.
320--
321mxDeactivate :: forall s. String -> MxAgent s MxAction
322mxDeactivate = return . MxAgentDeactivate
324-- | Continue executing (i.e., receiving and processing messages).
325--
326mxReady :: forall s. MxAgent s MxAction
327mxReady = return MxAgentReady
329-- | Causes the currently executing /event sink/ to be skipped.
330-- The remaining declared event sinks will be evaluated to find
331-- a matching handler. Can be used to allow multiple event sinks
332-- to process data of the same type.
333--
334mxSkip :: forall s. MxAgent s MxAction
335mxSkip = return MxAgentSkip
337-- | Continue exeucting, prioritising inputs from the process' own
338-- /mailbox/ ahead of data from the management event bus.
339--
340mxReceive :: forall s. MxAgent s MxAction
341mxReceive = return $ MxAgentPrioritise Mailbox
343-- | Continue exeucting, prioritising inputs from the management event bus
344-- over the process' own /mailbox/.
345--
346mxReceiveChan :: forall s. MxAgent s MxAction
347mxReceiveChan = return $ MxAgentPrioritise InputChan
349-- | Lift a @Process@ action.
350--
351liftMX :: Process a -> MxAgent s a
352liftMX p = MxAgent $ ST.lift p
354-- | Set the agent's local state.
355--
356mxSetLocal :: s -> MxAgent s ()
357mxSetLocal s = ST.modify $ \st -> st { mxLocalState = s }
359-- | Update the agent's local state.
360--
361mxUpdateLocal :: (s -> s) -> MxAgent s ()
362mxUpdateLocal f = ST.modify $ \st -> st { mxLocalState = (f $ mxLocalState st) }
364-- | Fetch the agent's local state.
365--
366mxGetLocal :: MxAgent s s
367mxGetLocal = ST.get >>= return . mxLocalState
369-- | Create an 'MxSink' from an expression taking a @Serializable@ type @m@,
370-- that yields an 'MxAction' in the 'MxAgent' monad.
371--
372mxSink :: forall s m . (Serializable m)
373 => (m -> MxAgent s MxAction)
374 -> MxSink s
375mxSink act msg = do
376 msg' <- liftMX $ (unwrapMessage msg :: Process (Maybe m))
377 case msg' of
378 Nothing -> return Nothing
379 Just m -> do
380 r <- act m
381 case r of
382 MxAgentSkip -> return Nothing
383 _ -> return $ Just r
385-- private ADT: a linked list of event sinks
386data MxPipeline s =
387 MxPipeline
388 {
389 current :: !(MxSink s)
390 , next :: !(MxPipeline s)
391 } | MxStop
393-- | Activates a new agent.
394--
395mxAgent :: MxAgentId -> s -> [MxSink s] -> Process ProcessId
396mxAgent mxId st hs = mxAgentWithFinalize mxId st hs $ return ()
398-- | Activates a new agent. This variant takes a /finalizer/ expression,
399-- that is run once the agent shuts down (even in case of failure/exceptions).
400-- The /finalizer/ expression runs in the mx monad - @MxAgent s ()@ - such
401-- that the agent's internal state remains accessible to the shutdown/cleanup
402-- code.
403--
404mxAgentWithFinalize :: MxAgentId
405 -> s
406 -> [MxSink s]
407 -> MxAgent s ()
408 -> Process ProcessId
409mxAgentWithFinalize mxId initState handlers dtor = do
410 let name = agentId mxId
411 existing <- whereis name
412 case existing of
413 Just _ -> die "DuplicateAgentId" -- TODO: better error handling policy
414 Nothing -> do
415 node <- processNode <$> ask
416 pid <- liftIO $ mxNew (localEventBus node) $ start
417 register name pid
418 return pid
419 where
420 start (sendTChan, recvTChan) = do
421 let nState = MxAgentState mxId sendTChan initState
422 runAgent dtor handlers InputChan recvTChan nState
424 runAgent :: MxAgent s ()
425 -> [MxSink s]
426 -> ChannelSelector
427 -> TChan Message
428 -> MxAgentState s
429 -> Process ()
430 runAgent eh hs cs c s =
431 runAgentWithFinalizer eh hs cs c s
432 `onException` runAgentFinalizer eh s
434 runAgentWithFinalizer :: MxAgent s ()
435 -> [MxSink s]
436 -> ChannelSelector
437 -> TChan Message
438 -> MxAgentState s
439 -> Process ()
440 runAgentWithFinalizer eh' hs' cs' c' s' = do
441 msg <- getNextInput cs' c'
442 (action, state) <- runPipeline msg s' $ pipeline hs'
443 case action of
444 MxAgentReady -> runAgent eh' hs' InputChan c' state
445 MxAgentPrioritise priority -> runAgent eh' hs' priority c' state
446 MxAgentDeactivate _ -> runAgentFinalizer eh' state
447 MxAgentSkip -> error "IllegalState"
448-- MxAgentBecome h' -> runAgent h' c state
450 getNextInput sel chan =
451 let matches =
452 case sel of
453 Mailbox -> [ matchAny return
454 , matchSTM (readTChan chan) return]
455 InputChan -> [ matchSTM (readTChan chan) return
456 , matchAny return]
457 in receiveWait matches
459 runAgentFinalizer :: MxAgent s () -> MxAgentState s -> Process ()
460 runAgentFinalizer f s = ST.runStateT (unAgent f) s >>= return . fst
462 pipeline :: forall s . [MxSink s] -> MxPipeline s
463 pipeline [] = MxStop
464 pipeline (sink:sinks) = MxPipeline sink (pipeline sinks)
466 runPipeline :: forall s .
467 Message
468 -> MxAgentState s
469 -> MxPipeline s
470 -> Process (MxAction, MxAgentState s)
471 runPipeline _ state MxStop = return (MxAgentReady, state)
472 runPipeline msg state MxPipeline{..} = do
473 let act = current msg
474 (pass, state') <- ST.runStateT (unAgent act) state
475 case pass of
476 Nothing -> runPipeline msg state next
477 Just result -> return (result, state')