git.iko.soy/distributed-process
on remove-table-api help sign in
476 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 , onException
258 , register
259 , whereis
260 , die
261 )
262import Control.Distributed.Process.Internal.Types
263 ( Process
264 , ProcessId
265 , Message
266 , LocalProcess(..)
267 , LocalNode(..)
268 , MxEventBus(..)
269 , unsafeCreateUnencodedMessage
270 )
271import Control.Distributed.Process.Management.Internal.Bus (publishEvent)
272import Control.Distributed.Process.Management.Internal.Types
273 ( MxAgentId(..)
274 , MxAgent(..)
275 , MxAction(..)
276 , ChannelSelector(..)
277 , MxAgentState(..)
278 , MxSink
279 , MxEvent(..)
280 )
281import Control.Distributed.Process.Serializable (Serializable)
282import Control.Monad.IO.Class (liftIO)
283import Control.Monad.Reader (ask)
284import qualified Control.Monad.State as ST
285 ( get
286 , modify
287 , lift
288 , runStateT
289 )
291-- | Publishes an arbitrary @Serializable@ message to the management event bus.
292-- Note that /no attempt is made to force the argument/, therefore it is very
293-- important that you do not pass unevaluated thunks that might crash the
294-- receiving process via this API, since /all/ registered agents will gain
295-- access to the data structure once it is broadcast by the agent controller.
296mxNotify :: (Serializable a) => a -> Process ()
297mxNotify msg = do
298 bus <- localEventBus . processNode <$> ask
299 liftIO $ publishEvent bus $ unsafeCreateUnencodedMessage msg
301--------------------------------------------------------------------------------
302-- API for writing user defined management extensions (i.e., agents) --
303--------------------------------------------------------------------------------
305-- | Return the 'MxAgentId' for the currently executing agent.
306--
307mxGetId :: MxAgent s MxAgentId
308mxGetId = ST.get >>= return . mxAgentId
310-- | The 'MxAgent' version of 'mxNotify'.
311--
312mxBroadcast :: (Serializable m) => m -> MxAgent s ()
313mxBroadcast msg = do
314 state <- ST.get
315 liftMX $ liftIO $ atomically $ do
316 writeTChan (mxBus state) (unsafeCreateUnencodedMessage msg)
318-- | Gracefully terminate an agent.
319--
320mxDeactivate :: forall s. String -> MxAgent s MxAction
321mxDeactivate = return . MxAgentDeactivate
323-- | Continue executing (i.e., receiving and processing messages).
324--
325mxReady :: forall s. MxAgent s MxAction
326mxReady = return MxAgentReady
328-- | Causes the currently executing /event sink/ to be skipped.
329-- The remaining declared event sinks will be evaluated to find
330-- a matching handler. Can be used to allow multiple event sinks
331-- to process data of the same type.
332--
333mxSkip :: forall s. MxAgent s MxAction
334mxSkip = return MxAgentSkip
336-- | Continue exeucting, prioritising inputs from the process' own
337-- /mailbox/ ahead of data from the management event bus.
338--
339mxReceive :: forall s. MxAgent s MxAction
340mxReceive = return $ MxAgentPrioritise Mailbox
342-- | Continue exeucting, prioritising inputs from the management event bus
343-- over the process' own /mailbox/.
344--
345mxReceiveChan :: forall s. MxAgent s MxAction
346mxReceiveChan = return $ MxAgentPrioritise InputChan
348-- | Lift a @Process@ action.
349--
350liftMX :: Process a -> MxAgent s a
351liftMX p = MxAgent $ ST.lift p
353-- | Set the agent's local state.
354--
355mxSetLocal :: s -> MxAgent s ()
356mxSetLocal s = ST.modify $ \st -> st { mxLocalState = s }
358-- | Update the agent's local state.
359--
360mxUpdateLocal :: (s -> s) -> MxAgent s ()
361mxUpdateLocal f = ST.modify $ \st -> st { mxLocalState = (f $ mxLocalState st) }
363-- | Fetch the agent's local state.
364--
365mxGetLocal :: MxAgent s s
366mxGetLocal = ST.get >>= return . mxLocalState
368-- | Create an 'MxSink' from an expression taking a @Serializable@ type @m@,
369-- that yields an 'MxAction' in the 'MxAgent' monad.
370--
371mxSink :: forall s m . (Serializable m)
372 => (m -> MxAgent s MxAction)
373 -> MxSink s
374mxSink act msg = do
375 msg' <- liftMX $ (unwrapMessage msg :: Process (Maybe m))
376 case msg' of
377 Nothing -> return Nothing
378 Just m -> do
379 r <- act m
380 case r of
381 MxAgentSkip -> return Nothing
382 _ -> return $ Just r
384-- private ADT: a linked list of event sinks
385data MxPipeline s =
386 MxPipeline
387 {
388 current :: !(MxSink s)
389 , next :: !(MxPipeline s)
390 } | MxStop
392-- | Activates a new agent.
393--
394mxAgent :: MxAgentId -> s -> [MxSink s] -> Process ProcessId
395mxAgent mxId st hs = mxAgentWithFinalize mxId st hs $ return ()
397-- | Activates a new agent. This variant takes a /finalizer/ expression,
398-- that is run once the agent shuts down (even in case of failure/exceptions).
399-- The /finalizer/ expression runs in the mx monad - @MxAgent s ()@ - such
400-- that the agent's internal state remains accessible to the shutdown/cleanup
401-- code.
402--
403mxAgentWithFinalize :: MxAgentId
404 -> s
405 -> [MxSink s]
406 -> MxAgent s ()
407 -> Process ProcessId
408mxAgentWithFinalize mxId initState handlers dtor = do
409 let name = agentId mxId
410 existing <- whereis name
411 case existing of
412 Just _ -> die "DuplicateAgentId" -- TODO: better error handling policy
413 Nothing -> do
414 node <- processNode <$> ask
415 pid <- liftIO $ mxNew (localEventBus node) $ start
416 register name pid
417 return pid
418 where
419 start (sendTChan, recvTChan) = do
420 let nState = MxAgentState mxId sendTChan initState
421 runAgent dtor handlers InputChan recvTChan nState
423 runAgent :: MxAgent s ()
424 -> [MxSink s]
425 -> ChannelSelector
426 -> TChan Message
427 -> MxAgentState s
428 -> Process ()
429 runAgent eh hs cs c s =
430 runAgentWithFinalizer eh hs cs c s
431 `onException` runAgentFinalizer eh s
433 runAgentWithFinalizer :: MxAgent s ()
434 -> [MxSink s]
435 -> ChannelSelector
436 -> TChan Message
437 -> MxAgentState s
438 -> Process ()
439 runAgentWithFinalizer eh' hs' cs' c' s' = do
440 msg <- getNextInput cs' c'
441 (action, state) <- runPipeline msg s' $ pipeline hs'
442 case action of
443 MxAgentReady -> runAgent eh' hs' InputChan c' state
444 MxAgentPrioritise priority -> runAgent eh' hs' priority c' state
445 MxAgentDeactivate _ -> runAgentFinalizer eh' state
446 MxAgentSkip -> error "IllegalState"
447-- MxAgentBecome h' -> runAgent h' c state
449 getNextInput sel chan =
450 let matches =
451 case sel of
452 Mailbox -> [ matchAny return
453 , matchSTM (readTChan chan) return]
454 InputChan -> [ matchSTM (readTChan chan) return
455 , matchAny return]
456 in receiveWait matches
458 runAgentFinalizer :: MxAgent s () -> MxAgentState s -> Process ()
459 runAgentFinalizer f s = ST.runStateT (unAgent f) s >>= return . fst
461 pipeline :: forall s . [MxSink s] -> MxPipeline s
462 pipeline [] = MxStop
463 pipeline (sink:sinks) = MxPipeline sink (pipeline sinks)
465 runPipeline :: forall s .
466 Message
467 -> MxAgentState s
468 -> MxPipeline s
469 -> Process (MxAction, MxAgentState s)
470 runPipeline _ state MxStop = return (MxAgentReady, state)
471 runPipeline msg state MxPipeline{..} = do
472 let act = current msg
473 (pass, state') <- ST.runStateT (unAgent act) state
474 case pass of
475 Nothing -> runPipeline msg state next
476 Just result -> return (result, state')