{-# LANGUAGE GeneralizedNewtypeDeriving #-}{-# LANGUAGE LambdaCase #-}{-# LANGUAGE ScopedTypeVariables #-}{-# LANGUAGE TupleSections #-}-- | A client of a daemon that speaks upstream's worker protocol, as-- upstream's remote store is one: the handshake as the client, then each-- operation it asks, its request, any upload after it, the daemon's-- messages while it works and the reply.---- == The session---- A t'ClientT' runs over a t'Transport', the daemon's side being the-- other end, after the handshake 'runClient' makes: the client offers the-- newest version it speaks and its features, and the session runs at the-- lower of the two numbers, with the features both list, refusing a-- daemon older than upstream's oldest. The core is pure: everything the-- client does to the world goes through the transport and the report the-- daemon's messages are given to ('relayMessage' gives them to a-- t'Logger').---- A session need not run in one call. 'openSession' makes the handshake-- and answers a t'ClientSession', which 'continueSession' runs steps-- over, any number of times, one call after another: the bytes the daemon-- sent that a step did not read stay with the session, and each call is-- given the transport and the report afresh. 'runClient' is the two-- together for a session that runs in one call.---- == Failures---- An operation the daemon fails is a 'DaemonFailed', which 'attempt'-- turns into a value, the session going on as upstream's does after an-- error its daemon sends; one the client will not send at the agreed-- version is a 'NotSent', which leaves the session as it was; and a-- connection that broke, or that the daemon sent bytes the protocol does-- not allow, is a 'ConnectionLost', after which nothing more is read.---- == Uploads---- An upload is framed, as from the versions every daemon serving it-- frames it. The daemon's messages are read on a thread of their own-- while the frames are written, so a daemon that says more during an add-- than the connection holds does not stall the upload, whatever the-- transport. An exception of the transport, or of the chunk source (a-- file that cannot be read), stops the reading and goes up out of the-- operation, and the session is not to be used again, its framed stream-- being cut short. An upload runs in 'IO', which the threads need.module Nix.Daemon.Client ( -- * The session ClientT, ClientFailure (..), runClient, ClientSession, openSession, continueSession, attempt, agreedVersion, daemonInfo, offeredVersion, -- * Operations setOptions, isValidPath, queryValidPaths, querySubstitutablePaths, queryReferrers, queryValidDerivers, queryDerivationOutputMap, queryAllValidPaths, queryPathInfo, queryMissing, addToStore, addToStoreNar, buildPaths, buildPathsWithResults, ensurePath, addTempRoot, addIndirectRoot, -- * The daemon's messages Relayed (..), relayed, Relay, newRelay, relayMessage, stopOpenActivities, disconnectedMessage, )whereimport Control.Concurrent (forkIOWithUnmask, killThread)import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)import Control.Exception (SomeException, mask, mask_, onException, throwIO, try)import Control.Monad (void, when)import Control.Monad.Except (ExceptT, MonadError, catchError, runExceptT, throwError)import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT)import qualified Control.Monad.Reader as Readerimport Control.Monad.State.Strict (MonadState, StateT, get, gets, modify', put, runStateT)import Control.Monad.Trans (lift)import Data.ByteString (ByteString)import qualified Data.ByteString as BSimport Data.ByteString.Builder (Builder)import qualified Data.ByteString.Char8 as BS8import Data.Foldable (traverse_)import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef)import Data.Map.Strict (Map)import qualified Data.Map.Strict as Mapimport Data.Set (Set)import qualified Data.Set as Setimport Data.Text (Text)import qualified Data.Text as Timport qualified Data.Text.Encoding as TEimport Data.Tuple (swap)import Data.Word (Word64)import Nix.Daemon.Connection (Transport (..))import Nix.Daemon.Ops (AddToStoreRequest, CheckSigs, ClientSettings, Repair, Request (..), Substitute, activityStart, buildResultsSince, outputMapSince, putRequest, queryMissingSince)import Nix.Daemon.Protocol ( Activity (..), ActivityId (..), BuildMode, DaemonError, DerivedPath, Field (..), HandshakeInfo, KeyedBuildResult, Missing, OutputName, StderrMessage (..), UnkeyedValidPathInfo, ValidPathInfo, Version (..), VersionNumber (..), featureDeleteDeadSpecificReferrers, featureDisableSetOptions, featureRealisationWithPath, getFeatures, getHandshakeInfo, getKeyedBuildResults, getMissing, getOutputMap, getServerMagic, getStderrMessage, getStorePathSet, getUnkeyedValidPathInfo, getValidPathInfo, getVersionNumber, latestVersionNumber, minimumVersionNumber, putClientMagic, putClientObsoleteFields, putFeatures, putVersionNumber, resBuildLogLine, resPostBuildLogLine, )import Nix.Daemon.Wire (DecodeError (..), Decoder, Decoding (..), feedInput, getBool, getWord64, putFrame, putFrameEnd, startDecoding)import Nix.Logger (ActivityStart, Level (..), Logger (..), logMessage)import Nix.Store.Path (StoreDir, StorePath)-- ----------------------------------------------------------------------------- The session-- ----------------------------------------------------------------------------- | Why an operation, or the session, did not get its answer.data ClientFailure = -- | The daemon failed the operation, with its error, which upstream's -- client throws as the daemon's. The session goes on, unless the -- daemon closed the connection with it, which the next operation -- finds. DaemonFailed !DaemonError | -- | The client will not send the operation at the agreed version, for -- the reason given; nothing was sent. NotSent !Text | -- | The connection broke, or the daemon sent what the protocol does -- not allow, for the reason given. Nothing more can be read. ConnectionLost !Text deriving (Eq, Show)-- | What every step of a session reads.data ClientEnv m = ClientEnv { ceStoreDir :: !StoreDir, ceTransport :: !(Transport m), ceReport :: !(StderrMessage -> m ()) }-- | What a session holds: the version agreed, what the daemon told the-- client, and the bytes the daemon sent that have not been read. It-- belongs to the connection it was opened on, whose daemon its bytes are.data ClientSession = ClientSession { sessVersion :: !Version, sessInfo :: !(Maybe HandshakeInfo), sessInput :: !ByteString }-- | A session before its handshake: nothing agreed or heard.unopenedSession :: ClientSessionunopenedSession = ClientSession (Version minimumVersionNumber Set.empty) Nothing BS.empty-- | A session's steps over the monad its transport runs in. A failure-- ends the steps that follow it unless 'attempt' catches it, and leaves-- what the session has read read, so a caught failure leaves the session-- where the daemon's bytes put it.newtype ClientT m a = ClientT (ReaderT (ClientEnv m) (ExceptT ClientFailure (StateT ClientSession m)) a) deriving (Functor, Applicative, Monad, MonadReader (ClientEnv m), MonadError ClientFailure, MonadState ClientSession)-- | Run an action in the transport's monad.inner :: (Monad m) => m a -> ClientT m ainner = ClientT . lift . lift . lift-- | The version this client offers: the newest number upstream speaks,-- with the features the codec carries and 'featureDisableSetOptions', as-- upstream's client offers it.offeredVersion :: VersionofferedVersion = Version latestVersionNumber (Set.fromList [featureRealisationWithPath, featureDeleteDeadSpecificReferrers, featureDisableSetOptions])-- | Make the handshake with a daemon over a transport, offering the-- version given ('offeredVersion' as upstream's client offers its own),-- naming paths under the store directory given, and giving what the-- daemon says as it works to the report; then run the session's steps.-- The session's input is the daemon's; nothing is closed here.runClient :: (Monad m) => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> ClientT m a -> m (Either ClientFailure a)runClient storeDir offered transport report steps = openSession storeDir offered transport report >>= \case Left failure -> pure (Left failure) Right session -> fst <$> continueSession storeDir transport report session steps-- | Make the handshake with a daemon over a transport, as 'runClient'-- does, and answer the session it made, for 'continueSession' to run-- steps over.openSession :: (Monad m) => StoreDir -> Version -> Transport m -> (StderrMessage -> m ()) -> m (Either ClientFailure ClientSession)openSession storeDir offered transport report = do (outcome, session) <- continueSession storeDir transport report unopenedSession (handshake offered) pure (session <$ outcome)-- | Run steps over a session opened earlier, over the transport it was-- opened on, the daemon's messages given to the report, and answer what-- the steps answer with the session as they leave it. A failed step-- leaves what it read read, and a 'ConnectionLost' leaves the session-- unusable, as 'attempt' says.continueSession :: StoreDir -> Transport m -> (StderrMessage -> m ()) -> ClientSession -> ClientT m a -> m (Either ClientFailure a, ClientSession)continueSession storeDir transport report = runSteps (ClientEnv storeDir transport report)-- | Run steps over what they read, given the session as it stands.runSteps :: ClientEnv m -> ClientSession -> ClientT m a -> m (Either ClientFailure a, ClientSession)runSteps env session (ClientT steps) = runStateT (runExceptT (runReaderT steps env)) session-- | Run steps, a failure of theirs answered as a value: what was read-- stays read, and a 'ConnectionLost' leaves the session unusable all the-- same.attempt :: (Monad m) => ClientT m a -> ClientT m (Either ClientFailure a)attempt steps = (Right <$> steps) `catchError` (pure . Left)-- | The version the session agreed.agreedVersion :: (Monad m) => ClientT m VersionagreedVersion = gets sessVersion-- | What the daemon told the client at the handshake.daemonInfo :: (Monad m) => ClientT m (Maybe HandshakeInfo)daemonInfo = gets sessInfo-- | The version a daemon's features are exchanged from.featureExchangeSince :: VersionNumberfeatureExchangeSince = VersionNumber 1 38-- | Agree a version with the daemon, as upstream's client does: send the-- opening word and the version offered together, read the daemon's word-- and number, refuse another major version or one older than upstream's-- oldest, and from 1.38 send the features offered and read the daemon's.-- Then send the obsolete fields, read what the daemon tells its client,-- and read its startup work to its end.handshake :: (Monad m) => Version -> ClientT m ()handshake offered = do send (putClientMagic <> putVersionNumber (versionNumber offered)) receive getServerMagic daemonNumber <- receive getVersionNumber when (vnMajor daemonNumber /= vnMajor latestVersionNumber) (throwError (ConnectionLost "Nix daemon protocol version not supported")) let agreed = min daemonNumber (versionNumber offered) when (agreed < minimumVersionNumber) (throwError (ConnectionLost "the Nix daemon version is too old")) daemonFeatures <- if agreed >= featureExchangeSince then send (putFeatures (versionFeatures offered)) *> receive getFeatures else pure Set.empty let version = Version agreed (Set.intersection daemonFeatures (versionFeatures offered)) modify' (\session -> session {sessVersion = version}) send (putClientObsoleteFields version) info <- receive (getHandshakeInfo version) modify' (\session -> session {sessInfo = Just info}) awaitWork-- | Upstream's words for a daemon that went away mid-session.disconnectedMessage :: TextdisconnectedMessage = "Nix daemon disconnected unexpectedly (maybe it crashed?)"-- | Read a value the daemon sends, the input after it kept.receive :: (Monad m) => Decoder a -> ClientT m areceive decoder = do held <- gets sessInput modify' (\session -> session {sessInput = BS.empty}) settle (if BS.null held then startDecoding decoder else feedInput (Just held) (startDecoding decoder)) where settle = \case Decoded value rest -> value <$ modify' (\session -> session {sessInput = rest}) DecodeFailed failure rest -> do modify' (\session -> session {sessInput = rest}) throwError (ConnectionLost (decodeFailure failure)) NeedInput more -> do transport <- asks ceTransport inner (transportReceive transport) >>= settle . more decodeFailure = \case InputEnded -> disconnectedMessage Malformed message -> message-- | Send bytes to the daemon.send :: (Monad m) => Builder -> ClientT m ()send bytes = do transport <- asks ceTransport inner (transportSend transport bytes)-- | Read the daemon's messages until its work on an operation is done,-- each given to the report, as upstream's client reads them: the end of-- the work ends the reading, and the daemon's error fails the operation.-- The client sends no upload unframed and has no sink, so a request for-- either is the daemon's breach of the session, in upstream's words.awaitWork :: (Monad m) => ClientT m ()awaitWork = do version <- gets sessVersion receive (getStderrMessage version) >>= \case StderrLast -> pure () StderrError failure -> throwError (DaemonFailed failure) StderrRead _ -> throwError (ConnectionLost "no source") StderrWrite _ -> throwError (ConnectionLost "no sink") message -> do report <- asks ceReport inner (report message) awaitWork-- ----------------------------------------------------------------------------- Requests-- ----------------------------------------------------------------------------- | A request as the client sends it at the agreed version, as-- 'putRequest' writes it, or why it is not sent: what 'putRequest'-- refuses, and an operation the version does not carry. Upstream's-- client works out a build's results, what is missing and a derivation's-- outputs itself when its daemon is older than the operation; this one-- does not send it.clientRequest :: StoreDir -> Version -> Request -> Either Text BuilderclientRequest storeDir version request = maybe (putRequest storeDir version request) Left (notCarried request) where notCarried = \case QueryMissing _ -> needs "QueryMissing" queryMissingSince QueryDerivationOutputMap _ -> needs "QueryDerivationOutputMap" outputMapSince BuildPathsWithResults _ _ -> needs "BuildPathsWithResults" buildResultsSince _ -> Nothing needs operation gate | versionNumber version >= gate = Nothing | otherwise = Just (operation <> " needs protocol 1." <> T.pack (show (vnMinor gate)) <> ", which the daemon does not speak")-- ----------------------------------------------------------------------------- Operations-- ----------------------------------------------------------------------------- | Send a request, and read the daemon's work to its end.perform :: (Monad m) => Request -> ClientT m ()perform request = sendRequest request *> awaitWork-- | Send a request as it is sent at the agreed version, or refuse it as-- 'NotSent'.sendRequest :: (Monad m) => Request -> ClientT m ()sendRequest request = do storeDir <- asks ceStoreDir version <- gets sessVersion written <- either (throwError . NotSent) pure (clientRequest storeDir version request) send written-- | Send a request, then an upload after it, framed from a chunk source-- that gives an empty chunk at its end, while the daemon's messages are-- read on a thread of their own, and read the daemon's work to its end.-- A failure of the daemon's work is the operation's, as for 'perform'; an-- exception of the transport or the chunk source stops the reading and-- goes up.performUploading :: Request -> IO ByteString -> ClientT IO ()performUploading request source = do sendRequest request env <- Reader.ask session <- get (outcome, afterWork) <- inner (fst <$> overlapped (runSteps env session awaitWork) (sendFrames (ceTransport env) source)) put afterWork either throwError pure outcome-- | Send the chunks a source gives as frames, and the end of the frames-- where it gives an empty one.sendFrames :: Transport IO -> IO ByteString -> IO ()sendFrames transport source = do chunk <- source if BS.null chunk then transportSend transport putFrameEnd else transportSend transport (putFrame chunk) *> sendFrames transport source-- | Run an action on a thread of its own while another runs on this one,-- and answer what both answered. An exception of this thread's action,-- or an interrupt of this thread, stops the other thread and waits for it-- to end before it goes up. An exception of the other thread's action is-- handed to this thread, which raises it once its own action has ended.overlapped :: IO a -> IO b -> IO (a, b)overlapped background foreground = mask $ \restore -> do outcome <- newEmptyMVar thread <- forkIOWithUnmask (\unmask -> try (unmask background) >>= putMVar outcome) let stop = killThread thread *> void (readMVar outcome) written <- restore foreground `onException` stop heard <- restore (readMVar outcome) `onException` stop either (\(err :: SomeException) -> throwIO err) (\value -> pure (value, written)) heard-- | Ask, then read the reply.ask :: (Monad m) => Request -> Decoder a -> ClientT m aask request reply = perform request *> receive reply-- | Ask, then read the word an operation with nothing else to say replies-- with.done :: (Monad m) => Request -> ClientT m ()done request = void (ask request getWord64)-- | The store directory paths are named under.storeDirOf :: (Monad m) => ClientT m StoreDirstoreDirOf = asks ceStoreDir-- | Send the client's settings for the rest of the session.setOptions :: (Monad m) => ClientSettings -> ClientT m ()setOptions settings = perform (SetOptions settings)-- | Whether a path is valid.isValidPath :: (Monad m) => StorePath -> ClientT m BoolisValidPath path = ask (IsValidPath path) getBool-- | Which of the paths are valid, having first substituted them where-- asked to.queryValidPaths :: (Monad m) => Set StorePath -> Substitute -> ClientT m (Set StorePath)queryValidPaths paths substitute = storeDirOf >>= ask (QueryValidPaths paths substitute) . getStorePathSet-- | Which of the paths a substituter offers.querySubstitutablePaths :: (Monad m) => Set StorePath -> ClientT m (Set StorePath)querySubstitutablePaths paths = storeDirOf >>= ask (QuerySubstitutablePaths paths) . getStorePathSet-- | The valid paths that refer to a path.queryReferrers :: (Monad m) => StorePath -> ClientT m (Set StorePath)queryReferrers path = storeDirOf >>= ask (QueryReferrers path) . getStorePathSet-- | The valid derivations that output a path.queryValidDerivers :: (Monad m) => StorePath -> ClientT m (Set StorePath)queryValidDerivers path = storeDirOf >>= ask (QueryValidDerivers path) . getStorePathSet-- | A derivation's outputs and the paths they have, where known.queryDerivationOutputMap :: (Monad m) => StorePath -> ClientT m (Map OutputName (Maybe StorePath))queryDerivationOutputMap path = storeDirOf >>= ask (QueryDerivationOutputMap path) . getOutputMap-- | Every valid path.queryAllValidPaths :: (Monad m) => ClientT m (Set StorePath)queryAllValidPaths = storeDirOf >>= ask QueryAllValidPaths . getStorePathSet-- | What the store records of a path, or 'Nothing' for a path that is not-- valid.queryPathInfo :: (Monad m) => StorePath -> ClientT m (Maybe UnkeyedValidPathInfo)queryPathInfo path = do storeDir <- storeDirOf version <- gets sessVersion ask (QueryPathInfo path) $ do valid <- getBool if valid then Just <$> getUnkeyedValidPathInfo storeDir version else pure Nothing-- | What realising the paths would build, substitute or not find.queryMissing :: (Monad m) => [DerivedPath] -> ClientT m MissingqueryMissing targets = storeDirOf >>= ask (QueryMissing targets) . getMissing-- | Make a content-addressed path from a dump, given the request and the-- dump as a chunk source that gives an empty chunk at its end, and answer-- the path's info.addToStore :: AddToStoreRequest -> IO ByteString -> ClientT IO ValidPathInfoaddToStore upload dump = do storeDir <- storeDirOf version <- gets sessVersion performUploading (AddToStore upload) dump receive (getValidPathInfo storeDir version)-- | Import a path from its NAR, given its info, whether a valid path's-- contents are replaced, whether its signatures are checked, and the NAR-- as a chunk source that gives an empty chunk where the archive ends.addToStoreNar :: ValidPathInfo -> Repair -> CheckSigs -> IO ByteString -> ClientT IO ()addToStoreNar info repair checkSigs = performUploading (AddToStoreNar info repair checkSigs)-- | Realise the paths.buildPaths :: (Monad m) => [DerivedPath] -> BuildMode -> ClientT m ()buildPaths targets mode = done (BuildPaths targets mode)-- | Realise the paths, with each one's result, keyed by the path as it was-- asked for.buildPathsWithResults :: (Monad m) => [DerivedPath] -> BuildMode -> ClientT m [KeyedBuildResult]buildPathsWithResults targets mode = do storeDir <- storeDirOf version <- gets sessVersion ask (BuildPathsWithResults targets mode) (getKeyedBuildResults storeDir version)-- | Make a path valid, substituting it if need be.ensurePath :: (Monad m) => StorePath -> ClientT m ()ensurePath = done . EnsurePath-- | Keep a path from collection while the session lasts.addTempRoot :: (Monad m) => StorePath -> ClientT m ()addTempRoot = done . AddTempRoot-- | Keep what a link names from collection while the link exists, given-- the bytes of the link's absolute path.addIndirectRoot :: (Monad m) => ByteString -> ClientT m ()addIndirectRoot = done . AddIndirectRoot-- ----------------------------------------------------------------------------- The daemon's messages-- ----------------------------------------------------------------------------- | What a message of the daemon's is to a logger.data Relayed = -- | A line the daemon logged, its trailing whitespace taken off. RelayedMessage !Text | -- | The store's activity the daemon started, under the number it gave -- it. RelayedStart !Word64 !ActivityStart | -- | A line a build's builder wrote, for the activity of that number. RelayedLine !Word64 !ByteString | -- | A line a post-build hook wrote. RelayedHookLine !ByteString | -- | The activity of that number stopped. RelayedStop !Word64 | -- | Nothing a logger takes: an activity that is not the store's, a -- result of another kind, a message about the connection itself. RelayedNothing deriving (Eq, Show)-- | What a message of the daemon's is to a logger, given the directory its-- paths are named under. A line of text is shown with any byte that is not-- UTF-8 replaced, since a logger takes text.relayed :: StoreDir -> StderrMessage -> Relayedrelayed storeDir = \case StderrNext line -> RelayedMessage (shown (BS8.dropWhileEnd isTrailingSpace line)) StderrStartActivity activity@Activity {actId = ActivityId number} -> maybe RelayedNothing (RelayedStart number) (activityStart storeDir activity) StderrResult (ActivityId number) kind (FieldString line : _) | kind == resBuildLogLine -> RelayedLine number line | kind == resPostBuildLogLine -> RelayedHookLine line StderrStopActivity (ActivityId number) -> RelayedStop number _ -> RelayedNothing where isTrailingSpace c = c `elem` [' ', '\n', '\r', '\t']-- | What a logger has of the activities a daemon started: the sink for-- each one's builder lines and the action that stops it, by the number the-- daemon gave it, and the logger itself.data Relay = Relay { relayStoreDir :: !StoreDir, relayLogger :: !Logger, relayOpen :: !(IORef (Map Word64 (ByteString -> IO (), IO ()))) }-- | A relay to a logger for the daemon of a store directory, with no-- activity open.newRelay :: StoreDir -> Logger -> IO RelaynewRelay storeDir logger = Relay storeDir logger <$> newIORef Map.empty-- | Give a daemon's message to the logger as the same calls the store-- makes for the same work: a line as a message at the error level, as-- upstream's client reports one, a build's or a substitution's start as an-- activity of the logger, its builder's lines as that activity's, and its-- stop as the activity's. A builder line of an activity that is not open-- is a build line of the logger, and a post-build hook's line a message-- after @post-build-hook: @. An activity started under a number already-- open stops the one it replaces.---- An activity is started and kept in one step that asynchronous-- exceptions do not interrupt, so one that stops the thread reading the-- daemon's messages (an upload whose source fails) cannot leave an-- activity started and not kept, which nothing would stop. A blocking-- call of the logger can still be interrupted.relayMessage :: Relay -> StderrMessage -> IO ()relayMessage relay message = case relayed (relayStoreDir relay) message of RelayedMessage text -> logAt logger LevelError text RelayedStart number start -> mask_ (logActivity logger start >>= openActivity relay number) RelayedLine number line -> readIORef (relayOpen relay) >>= \held -> maybe (logBuildLine logger line) (\(sink, _) -> sink line) (Map.lookup number held) RelayedHookLine line -> logMessage logger ("post-build-hook: " <> shown line) RelayedStop number -> closeActivity relay number RelayedNothing -> pure () where logger = relayLogger relay-- | Keep an activity under its number, stopping one already open under it.openActivity :: Relay -> Word64 -> (ByteString -> IO (), IO ()) -> IO ()openActivity relay number activity = do replaced <- atomicModifyIORef' (relayOpen relay) (swap . Map.insertLookupWithKey (\_ new _ -> new) number activity) traverse_ snd replaced-- | Stop the activity open under a number and forget it.closeActivity :: Relay -> Word64 -> IO ()closeActivity relay number = do stopping <- atomicModifyIORef' (relayOpen relay) (\held -> (Map.delete number held, Map.lookup number held)) traverse_ snd stopping-- | Stop every activity still open, latest first, and forget them: the-- ones an operation that failed left started.stopOpenActivities :: Relay -> IO ()stopOpenActivities relay = do open <- atomicModifyIORef' (relayOpen relay) (Map.empty,) traverse_ snd (reverse (Map.elems open))-- | Bytes shown as text, any that are not UTF-8 replaced.shown :: ByteString -> Textshown = TE.decodeUtf8Lenient