module Remote.Init (remoteInit) where
import qualified Prelude as Prelude
import Prelude hiding (lookup)
import Remote.Peer (startDiscoveryService)
import Remote.Task (__remoteCallMetaData)
import Remote.Process (startProcessRegistryService,suppressTransmitException,localRegistryRegisterNode,localRegistryHello,localRegistryUnregisterNode,
startProcessMonitorService,startNodeMonitorService,startLoggingService,startSpawnerService,ProcessM,readConfig,initNode,startLocalRegistry,
forkAndListenAndDeliver,waitForThreads,roleDispatch,Node,runLocalProcess,performFinalization,startFinalizerService)
import Remote.Reg (registerCalls,RemoteCallMetaData)
import System.Environment (getEnvironment)
import Control.Concurrent (threadDelay)
import Control.Monad.Trans (liftIO)
import Control.Exception (finally)
import Control.Concurrent.MVar (MVar,takeMVar,putMVar,newEmptyMVar)
startServices :: ProcessM ()
startServices =
do
startProcessRegistryService
startNodeMonitorService
startProcessMonitorService
startLoggingService
startDiscoveryService
startSpawnerService
startFinalizerService (suppressTransmitException localRegistryUnregisterNode >> return ())
dispatchServices :: MVar Node -> IO ()
dispatchServices node = do mv <- newEmptyMVar
_ <- runLocalProcess node (startServices >> liftIO (putMVar mv ()))
takeMVar mv
remoteInit :: Maybe FilePath -> [RemoteCallMetaData] -> (String -> ProcessM ()) -> IO ()
remoteInit defaultConfig metadata f =
let
defaultMetaData = [Remote.Task.__remoteCallMetaData]
lookup = registerCalls (defaultMetaData ++ metadata)
in
do
configFileName <- getConfigFileName
cfg <- readConfig True configFileName
node <- initNode cfg lookup
_ <- startLocalRegistry cfg False
forkAndListenAndDeliver node cfg
dispatchServices node
(roleDispatch node userFunction >> waitForThreads node) `finally` (performFinalization node)
threadDelay 500000
where getConfigFileName = do env <- getEnvironment
return $ maybe defaultConfig Just (Prelude.lookup "RH_CONFIG" env)
userFunction s = localRegistryHello >> localRegistryRegisterNode >> f s