{-# LANGUAGE OverloadedStrings, DoAndIfThenElse #-}
module IHaskell.IPython.ZeroMQ (
ZeroMQInterface(..),
ZeroMQStdin(..),
serveProfile,
serveStdin,
ZeroMQEphemeralPorts,
withEphemeralPorts,
) where
import Control.Concurrent
import Control.Exception
import Control.Monad
import qualified Crypto.Hash as Hash
import Crypto.Hash.Algorithms (SHA256)
import qualified Crypto.MAC.HMAC as HMAC
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as Char
import qualified Data.ByteString.Lazy as LBS
import Data.Char
import Data.Monoid ((<>))
import qualified Data.Text.Encoding as Text
import System.ZMQ4 as ZMQ4 hiding (stdin)
import Text.Read (readMaybe)
import IHaskell.IPython.Message.Parser
import IHaskell.IPython.Message.Writer ()
import IHaskell.IPython.Types
data ZeroMQInterface =
Channels
{
shellRequestChannel :: Chan Message
, shellReplyChannel :: Chan Message
, controlRequestChannel :: Chan Message
, controlReplyChannel :: Chan Message
, iopubChannel :: Chan Message
, hmacKey :: ByteString
}
data ZeroMQStdin =
StdinChannel
{ stdinRequestChannel :: Chan Message
, stdinReplyChannel :: Chan Message
}
newZeroMQInterface :: ByteString -> IO ZeroMQInterface
newZeroMQInterface key = do
shellReqChan <- newChan
shellRepChan <- newChan
controlReqChan <- dupChan shellReqChan
controlRepChan <- dupChan shellRepChan
iopubChan <- newChan
return $! Channels
{ shellRequestChannel = shellReqChan
, shellReplyChannel = shellRepChan
, controlRequestChannel = controlReqChan
, controlReplyChannel = controlRepChan
, iopubChannel = iopubChan
, hmacKey = key
}
serveProfile :: Profile
-> Bool
-> IO ZeroMQInterface
serveProfile profile debug = do
channels <- newZeroMQInterface (signatureKey profile)
forkIO $ withContext $ \context -> do
forkIO $ serveSocket context Rep (hbPort profile) $ heartbeat channels
forkIO $ serveSocket context Router (controlPort profile) $ control debug channels
forkIO $ serveSocket context Router (shellPort profile) $ shell debug channels
serveSocket context Pub (iopubPort profile) $ iopub debug channels
return channels
data ZeroMQEphemeralPorts =
ZeroMQEphemeralPorts
{ ephHbPort :: !Port
, ephControlPort :: !Port
, ephShellPort :: !Port
, ephIOPubPort :: !Port
, ephSignatureKey :: !ByteString
}
instance ToJSON ZeroMQEphemeralPorts where
toJSON ports =
object
[ "ip" .= ("127.0.0.1" :: String)
, "transport" .= TCP
, "control_port" .= ephControlPort ports
, "hb_port" .= ephHbPort ports
, "shell_port" .= ephShellPort ports
, "iopub_port" .= ephIOPubPort ports
, "key" .= Text.decodeUtf8 (ephSignatureKey ports)
]
parsePort :: String -> Maybe Int
parsePort s = readMaybe num
where
num = reverse (takeWhile isNumber (reverse s))
bindLocalEphemeralPort :: Socket a -> IO Int
bindLocalEphemeralPort socket = do
bind socket $ "tcp://127.0.0.1:*"
endpointString <- lastEndpoint socket
case parsePort endpointString of
Nothing ->
fail $ "internalError: IHaskell.IPython.ZeroMQ.bindLocalEphemeralPort encountered a port index that could not be interpreted as an int."
Just endpointIndex ->
return endpointIndex
withEphemeralPorts :: ByteString
-> Bool
-> (ZeroMQEphemeralPorts
-> ZeroMQInterface
-> IO a)
-> IO a
withEphemeralPorts key debug callback = do
channels <- newZeroMQInterface key
withContext $ \context -> do
withSocket context Rep $ \heartbeatSocket -> do
withSocket context Router $ \controlportSocket -> do
withSocket context Router $ \shellportSocket -> do
withSocket context Pub $ \iopubSocket -> do
hbPort <- bindLocalEphemeralPort heartbeatSocket
controlPort <- bindLocalEphemeralPort controlportSocket
shellPort <- bindLocalEphemeralPort shellportSocket
iopubPort <- bindLocalEphemeralPort iopubSocket
let ports = ZeroMQEphemeralPorts { ephHbPort = hbPort, ephControlPort = controlPort, ephShellPort = shellPort, ephIOPubPort = iopubPort, ephSignatureKey = key }
_ <- forkIO $ forever $ heartbeat channels heartbeatSocket
_ <- forkIO $ forever $ control debug channels controlportSocket
_ <- forkIO $ forever $ shell debug channels shellportSocket
_ <- forkIO $ checkedIOpub debug channels iopubSocket
callback ports channels
serveStdin :: Profile -> IO ZeroMQStdin
serveStdin profile = do
reqChannel <- newChan
repChannel <- newChan
forkIO $ withContext $ \context ->
serveSocket context Router (stdinPort profile) $ \socket -> do
readChan reqChannel >>= sendMessage False (signatureKey profile) socket
receiveMessage False socket >>= writeChan repChannel
return $ StdinChannel reqChannel repChannel
serveSocket :: SocketType a => Context -> a -> Port -> (Socket a -> IO b) -> IO ()
serveSocket context socketType port action = void $
withSocket context socketType $ \socket -> do
bind socket $ "tcp://127.0.0.1:" ++ show port
forever $ action socket
heartbeat :: ZeroMQInterface -> Socket Rep -> IO ()
heartbeat _ socket = do
request <- receive socket
send socket [] request
shell :: Bool -> ZeroMQInterface -> Socket Router -> IO ()
shell debug channels socket = do
receiveMessage debug socket >>= writeChan requestChannel
readChan replyChannel >>= sendMessage debug (hmacKey channels) socket
where
requestChannel = shellRequestChannel channels
replyChannel = shellReplyChannel channels
control :: Bool -> ZeroMQInterface -> Socket Router -> IO ()
control debug channels socket = do
receiveMessage debug socket >>= writeChan requestChannel
readChan replyChannel >>= sendMessage debug (hmacKey channels) socket
where
requestChannel = controlRequestChannel channels
replyChannel = controlReplyChannel channels
iopub :: Bool -> ZeroMQInterface -> Socket Pub -> IO ()
iopub debug channels socket =
readChan (iopubChannel channels) >>= sendMessage debug (hmacKey channels) socket
trySendMessage :: Sender a => String -> Bool -> ByteString -> Socket a -> Message -> IO Bool
trySendMessage nm debug hmacKey socket message = do
let zmqErrorHandler :: ZMQError -> IO Bool
zmqErrorHandler e
| errno e == 38 = return False
| otherwise = throwIO e
(sendMessage debug hmacKey socket message >> return True) `catch` zmqErrorHandler
checkedIOpub :: Bool -> ZeroMQInterface -> Socket Pub -> IO ()
checkedIOpub debug channels socket = do
msg <- readChan (iopubChannel channels)
cont <- trySendMessage "io" debug (hmacKey channels) socket msg
when cont $
checkedIOpub debug channels socket
receiveMessage :: Receiver a => Bool -> Socket a -> IO Message
receiveMessage debug socket = do
idents <- readUntil "<IDS|MSG>"
void next
headerData <- next
parentHeader <- next
metadata <- next
content <- next
when debug $ do
putStr "Header: "
Char.putStrLn headerData
putStr "Content: "
Char.putStrLn content
let message = parseMessage idents headerData parentHeader metadata content
return message
where
next = receive socket
readUntil str = do
line <- next
if line /= str
then do
remaining <- readUntil str
return $ line : remaining
else return []
sendMessage :: Sender a => Bool -> ByteString -> Socket a -> Message -> IO ()
sendMessage _ _ _ SendNothing = return ()
sendMessage debug hmacKey socket message = do
when debug $ do
putStr "Message: "
print message
putStr "Sent: "
print content
mapM_ sendPiece idents
sendPiece "<IDS|MSG>"
sendPiece signature
sendPiece headStr
sendPiece parentHeaderStr
sendPiece metadata
sendLast content
where
sendPiece = send socket [SendMore]
sendLast = send socket []
encodeStrict :: ToJSON a => a -> ByteString
encodeStrict = LBS.toStrict . encode
signature :: ByteString
signature = hmac $ headStr <> parentHeaderStr <> metadata <> content
hmac :: ByteString -> ByteString
hmac = Char.pack . show . (HMAC.hmacGetDigest :: HMAC.HMAC SHA256 -> Hash.Digest SHA256) . HMAC.hmac hmacKey
head = header message
parentHeaderStr = maybe "{}" encodeStrict $ parentHeader head
idents = identifiers head
metadata = "{}"
content = encodeStrict message
headStr = encodeStrict head