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-----------------------------------------------------------------------------
13-- Module : Control.Distributed.Process.Management
14-- Copyright : (c) Well-Typed / Tim Watson
15-- License : BSD3 (see the file LICENSE)
17-- Maintainer : Tim Watson <watson.timothy@gmail.com>
18-- Stability : experimental
19-- Portability : non-portable (requires concurrency)
21-- [Management Extensions API]
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.
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.
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).
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.
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.
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.
69-- [Management API Semantics]
71-- The management API provides /no guarantees whatsoever/, viz:
73-- * The ordering of messages delivered to the event bus.
75-- * The order in which agents will be executed.
77-- * Whether messages will be taken from the mailbox first, or the event bus.
79-- [Management Data API]
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 /data tables/.
88-- Each agent is assigned its own data table, which acts as a shared map, where
89-- the keys are @String@s and the values are @Serializable@ datum of whatever
90-- type the agent or its clients stores.
92-- Because an agent's /data table/ stores its values in raw 'Message' format,
93-- it works effectively as an /un-typed dictionary/, into which data of varying
94-- types can be fed and later retrieved. The upside of this is that different
95-- keys can be mapped to various types without any additional work on the part
96-- of the developer. The downside is that the code reading these values must
97-- know in advance what type(s) to expect, and the API provides no additional
98-- support for handling that.
100-- Publishing is accomplished using the 'mxPublish' and 'mxSet' APIs, whilst
101-- querying and deletion are handled by 'mxGet', 'mxClear', 'mxPurgeTable' and
102-- 'mxDropTable' respectively.
104-- When a management agent terminates, their tables are left in memory despite
105-- termination, such that an agent may resume its role (by restarting) or have
106-- its 'MxAgentId' taken over by another subsequent agent, leaving the data
107-- originally captured in place.
111-- New agents are defined with 'mxAgent' and require a unique 'MxAgentId', an
112-- initial state - 'MxAgent' runs in a state transformer - and a list of the
113-- agent's event sinks. Each 'MxSink' is defined in terms of a specific
114-- @Serializable@ type, via the 'mxSink' function, binding the event handler
115-- expression to inputs of only that type.
117-- Apart from modifying its own local state, an agent can execute arbitrary
118-- @Process a@ code via lifting (see 'liftMX') and even publish its own messages
119-- back to the primary event bus (see 'mxBroadcast').
121-- Since messages are delivered to agents from both the management event bus and
122-- the agent processes mailbox, agents (i.e., event sinks) will generally have
123-- no idea as to their origin. An agent can, however, choose to prioritise the
124-- choice of input (source) each time one of its event sinks runs. The /standard/
125-- way for an event sink to indicate that the agent is ready for its next input
126-- is to evaluate 'mxReady'. When this happens, the management infrastructure
127-- will obtain data from the event bus and process' mailbox in a round robbin
128-- fashion, i.e., one after the other, changing each time.
132-- What follows is a grossly over-simplified example of a management agent that
133-- provides a basic name monitoring facility. Whenever a process name is
134-- registered or unregistered, clients are informed of the fact.
136-- > -- simple notification data type
138-- > data Registration = Reg { added :: Bool
139-- > , procId :: ProcessId
143-- > -- start a /name monitoring agent/
144-- > nameMonitorAgent = do
145-- > mxAgent (MxAgentId "name-monitor") Set.empty [
146-- > (mxSink $ \(pid :: ProcessId) -> do
147-- > mxUpdateState $ Set.insert pid
152-- > (MxRegistered p n) -> notify True n p
153-- > (MxUnRegistered p n) -> notify False n p
158-- > notify a n p = do
159-- > Foldable.mapM_ (liftMX . deliver (Reg a n p)) =<< mxGetLocal
162-- The client interface (for sending their pid) can take one of two forms:
164-- > monitorNames = getSelfPid >>= nsend "name-monitor"
165-- > monitorNames2 = getSelfPid >>= mxNotify
167-- For some real-world examples, see the distributed-process-platform package.
169-- [Performance, Stablity and Scalability]
171-- /Management Agents/ offer numerous advantages over regular processes:
172-- broadcast communication with them can have a lower latency, they offer
173-- simplified messgage (i.e., input type) handling and they have access to
174-- internal system information that would be otherwise unobtainable.
176-- Do not be tempted to implement everything (e.g., the kitchen sink) using the
177-- management API though. There are overheads associated with management agents
178-- which is why they're presented as tools for consuming low level system
179-- information, instead of as /application level/ development tools.
181-- Agents that rely heavily on a busy mailbox can cause the management event
182-- bus to backlog un-GC'ed data, leading to increased heap space. Producers that
183-- do not take care to avoid passing unevaluated thunks to the API can crash
184-- /all/ the agents in the system. Agents are not monitored or managed in any
185-- way, and those that crash will not be restarted.
187-- The management event bus can receive a great deal of traffic. Every time
188-- a message is sent and/or received, an event is passed to the agent controller
189-- and broadcast to all agents (plus the trace controller, if tracing is enabled
190-- for the node). This is already a significant overhead - though profiling and
191-- benchmarks have demonstrated that it does not adversely affect performance
192-- if few agents are installed. Agents will typically use more cycles than plain
193-- processes, since they perform additional work: selecting input data from both
194-- the event bus /and/ their own mailboxes, plus searching through the set of
195-- event sinks (for each agent) to determine the right handler for the event.
197-- Each management agent requires not only its own @Process@ (in which the agent
198-- code is run), but also a peer process that provides its /data table/. These
199-- data tables also have to be coordinated and manaaged on each agent's behalf.
201-- [Architecture Overview]
203-- The architecture of the management event bus is internal and subject to
204-- change without prior notice. The description that follows is provided for
205-- informational purposes only.
207-- When a node initially starts, two special, internal system processes are
208-- started to support the management infrastructure. The first, known as the
209-- /trace controller/, is responsible for consuming 'MxEvent's and forwarding
210-- them to the configured tracer - see "Control.Distributed.Process.Debug" for
211-- further details. The second is the /management agent controller/, and is the
212-- primary worker process underpinning the management infrastructure. All
213-- published management events are routed to this process, which places them
214-- onto a system wide /event bus/ and additionally passes them directly to the
215-- /trace controller/.
217-- There are several reasons for segregating the tracing and management control
218-- planes in this fashion. Tracing can be enabled or disabled by clients, whilst
219-- the management event bus cannot, since in addition to providing
220-- runtime instrumentation, its intended use-cases include node monitoring, peer
221-- discovery (via topology providing backends) and other essential system
222-- services that require knowledge of otherwise hidden system internals. Tracing
223-- is also subject to /trace flags/ that limit the specific 'MxEvent's delivered
224-- to trace clients - an overhead/complexity not shared by management agents.
225-- Finally, tracing and management agents are implemented using completely
226-- different signalling techniques - more on this later - which would introduce
227-- considerable complexity if the shared the same /event loop/.
229-- The management control plane is driven by a shared broadcast channel, which
230-- is written to by the agent controller and subscribed to by all agent
231-- processes. Agents are spawned as regular processes, whose primary
232-- implementation (i.e., /server loop/) is responsible for consuming
233-- messages from both the broadcast channel and their own mailbox. Once
234-- consumed, messages are applied to the agent's /event sinks/ until one
235-- matches the input, at which point it is applied and the loop continues.
236-- The implementation chooses from the event bus and the mailbox in a
237-- round-robin fashion, until a message is received. This polling activity would
238-- lead to management agents consuming considerable system resources if left
239-- unchecked, therefore the implementation will poll for a limitted number of
240-- retries, after which it will perform a blocking read on the event bus.
242-----------------------------------------------------------------------------
243module Control.Distributed.Process.Management
246 -- * Firing Arbitrary /Mx Events/
248 -- * Constructing Mx Agents
253 , mxAgentWithFinalize
276import Control.Applicative ((<$>))
277import Control.Concurrent.STM (atomically)
278import Control.Concurrent.STM.TChan
283import Control.Distributed.Process.Internal.Primitives
296import Control.Distributed.Process.Internal.Types
303 , unsafeCreateUnencodedMessage
305import Control.Distributed.Process.Management.Internal.Bus (publishEvent)
306import qualified Control.Distributed.Process.Management.Internal.Table as Table
307import Control.Distributed.Process.Management.Internal.Types
311 , ChannelSelector(..)
317import Control.Distributed.Process.Serializable (Serializable)
318import Control.Monad.IO.Class (liftIO)
319import Control.Monad.Reader (ask)
320import qualified Control.Monad.State as ST
327-- | Publishes an arbitrary @Serializable@ message to the management event bus.
328-- Note that /no attempt is made to force the argument/, therefore it is very
329-- important that you do not pass unevaluated thunks that might crash the
330-- receiving process via this API, since /all/ registered agents will gain
331-- access to the data structure once it is broadcast by the agent controller.
332mxNotify :: (Serializable a) => a -> Process ()
334 bus <- localEventBus . processNode <$> ask
335 liftIO $ publishEvent bus $ unsafeCreateUnencodedMessage msg
337-- | Publish an arbitrary @Message@ as a property in the management database.
339-- For publishing @Serializable@ data, use 'mxSet' instead.
341mxPublish :: MxAgentId -> String -> Message -> Process ()
342mxPublish a k v = Table.set k v (Table.MxForAgent a)
344-- | Sets an arbitrary @Serializable@ datum against a key in the management
345-- database. Note that /no attempt is made to force the argument/, therefore
346-- it is very important that you do not pass unevaluated thunks that might
347-- crash some other, arbitrary process (or management agent!) that obtains
348-- and attempts to force the value later on.
350mxSet :: Serializable a => MxAgentId -> String -> a -> Process ()
351mxSet mxId key msg = do
352 Table.set key (unsafeCreateUnencodedMessage msg) (Table.MxForAgent mxId)
354-- | Fetches a property from the management database for the given key.
355-- If the property is not set, or does not match the expected type when
356-- typechecked (at runtime), returns @Nothing@.
357mxGet :: Serializable a => MxAgentId -> String -> Process (Maybe a)
358mxGet = Table.fetch . Table.MxForAgent
360-- | Clears a property from the management database using the given key.
361-- If the key does not exist in the database, this is a noop.
362mxClear :: MxAgentId -> String -> Process ()
363mxClear mxId key = Table.clear key (Table.MxForAgent mxId)
365-- | Purges a table in the management database of all its stored properties.
366mxPurgeTable :: MxAgentId -> Process ()
367mxPurgeTable = Table.purge . Table.MxForAgent
369-- | Deletes a table from the management database.
370mxDropTable :: MxAgentId -> Process ()
371mxDropTable = Table.delete . Table.MxForAgent
373--------------------------------------------------------------------------------
374-- API for writing user defined management extensions (i.e., agents) --
375--------------------------------------------------------------------------------
377-- | Return the 'MxAgentId' for the currently executing agent.
379mxGetId :: MxAgent s MxAgentId
380mxGetId = ST.get >>= return . mxAgentId
382-- | The 'MxAgent' version of 'mxNotify'.
384mxBroadcast :: (Serializable m) => m -> MxAgent s ()
387 liftMX $ liftIO $ atomically $ do
388 writeTChan (mxBus state) (unsafeCreateUnencodedMessage msg)
390-- | Gracefully terminate an agent.
392mxDeactivate :: forall s. String -> MxAgent s MxAction
393mxDeactivate = return . MxAgentDeactivate
395-- | Continue executing (i.e., receiving and processing messages).
397mxReady :: forall s. MxAgent s MxAction
398mxReady = return MxAgentReady
400-- | Causes the currently executing /event sink/ to be skipped.
401-- The remaining declared event sinks will be evaluated to find
402-- a matching handler. Can be used to allow multiple event sinks
403-- to process data of the same type.
405mxSkip :: forall s. MxAgent s MxAction
406mxSkip = return MxAgentSkip
408-- | Continue exeucting, prioritising inputs from the process' own
409-- /mailbox/ ahead of data from the management event bus.
411mxReceive :: forall s. MxAgent s MxAction
412mxReceive = return $ MxAgentPrioritise Mailbox
414-- | Continue exeucting, prioritising inputs from the management event bus
415-- over the process' own /mailbox/.
417mxReceiveChan :: forall s. MxAgent s MxAction
418mxReceiveChan = return $ MxAgentPrioritise InputChan
420-- | Lift a @Process@ action.
422liftMX :: Process a -> MxAgent s a
423liftMX p = MxAgent $ ST.lift p
425-- | Set the agent's local state.
427mxSetLocal :: s -> MxAgent s ()
428mxSetLocal s = ST.modify $ \st -> st { mxLocalState = s }
430-- | Update the agent's local state.
432mxUpdateLocal :: (s -> s) -> MxAgent s ()
433mxUpdateLocal f = ST.modify $ \st -> st { mxLocalState = (f $ mxLocalState st) }
435-- | Fetch the agent's local state.
437mxGetLocal :: MxAgent s s
438mxGetLocal = ST.get >>= return . mxLocalState
440-- | Create an 'MxSink' from an expression taking a @Serializable@ type @m@,
441-- that yields an 'MxAction' in the 'MxAgent' monad.
443mxSink :: forall s m . (Serializable m)
444 => (m -> MxAgent s MxAction)
447 msg' <- liftMX $ (unwrapMessage msg :: Process (Maybe m))
449 Nothing -> return Nothing
453 MxAgentSkip -> return Nothing
456-- private ADT: a linked list of event sinks
460 current :: !(MxSink s)
461 , next :: !(MxPipeline s)
464-- | Activates a new agent.
466mxAgent :: MxAgentId -> s -> [MxSink s] -> Process ProcessId
467mxAgent mxId st hs = mxAgentWithFinalize mxId st hs $ return ()
469-- | Activates a new agent. This variant takes a /finalizer/ expression,
470-- that is run once the agent shuts down (even in case of failure/exceptions).
471-- The /finalizer/ expression runs in the mx monad - @MxAgent s ()@ - such
472-- that the agent's internal state remains accessible to the shutdown/cleanup
475mxAgentWithFinalize :: MxAgentId
480mxAgentWithFinalize mxId initState handlers dtor = do
481 let name = agentId mxId
482 existing <- whereis name
484 Just _ -> die "DuplicateAgentId" -- TODO: better error handling policy
486 node <- processNode <$> ask
487 pid <- liftIO $ mxNew (localEventBus node) $ start
491 start (sendTChan, recvTChan) = do
493 nsend Table.mxTableCoordinator (MxAgentStart sp mxId)
494 tablePid <- receiveWait [ matchChan rp (\(p :: ProcessId) -> return p) ]
495 let nState = MxAgentState mxId sendTChan tablePid initState
496 runAgent dtor handlers InputChan recvTChan nState
498 runAgent :: MxAgent s ()
504 runAgent eh hs cs c s =
505 runAgentWithFinalizer eh hs cs c s
506 `onException` runAgentFinalizer eh s
508 runAgentWithFinalizer :: MxAgent s ()
514 runAgentWithFinalizer eh' hs' cs' c' s' = do
515 msg <- getNextInput cs' c'
516 (action, state) <- runPipeline msg s' $ pipeline hs'
518 MxAgentReady -> runAgent eh' hs' InputChan c' state
519 MxAgentPrioritise priority -> runAgent eh' hs' priority c' state
520 MxAgentDeactivate _ -> runAgentFinalizer eh' state
521 MxAgentSkip -> error "IllegalState"
522-- MxAgentBecome h' -> runAgent h' c state
524 getNextInput sel chan =
527 Mailbox -> [ matchAny return
528 , matchSTM (readTChan chan) return]
529 InputChan -> [ matchSTM (readTChan chan) return
531 in receiveWait matches
533 runAgentFinalizer :: MxAgent s () -> MxAgentState s -> Process ()
534 runAgentFinalizer f s = ST.runStateT (unAgent f) s >>= return . fst
536 pipeline :: forall s . [MxSink s] -> MxPipeline s
538 pipeline (sink:sinks) = MxPipeline sink (pipeline sinks)
540 runPipeline :: forall s .
544 -> Process (MxAction, MxAgentState s)
545 runPipeline _ state MxStop = return (MxAgentReady, state)
546 runPipeline msg state MxPipeline{..} = do
547 let act = current msg
548 (pass, state') <- ST.runStateT (unAgent act) state
550 Nothing -> runPipeline msg state next
551 Just result -> return (result, state')
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