Andrea Vezzosi pushed to branch wip/romes/async-rpc at Glasgow Haskell Compiler / GHC

Commits:

4 changed files:

Changes:

  • compiler/GHC/Runtime/Interpreter.hs
    ... ... @@ -115,12 +115,14 @@ import Control.Monad.STM
    115 115
     import Data.Binary
    
    116 116
     import Data.ByteString (ByteString)
    
    117 117
     import qualified Data.ByteString.Short as SBS
    
    118
    +import Data.IORef
    
    118 119
     import qualified GHC.Exts.Heap as Heap
    
    119 120
     import GHC.Stack.CCS (CostCentre,CostCentreStack)
    
    120 121
     import System.Directory
    
    121 122
     import System.Process
    
    122 123
     import System.Timeout (timeout)
    
    123 124
     import qualified GHC.InfoProv as InfoProv
    
    125
    +import System.Exit
    
    124 126
     
    
    125 127
     import GHC.Builtin.Modules( gHC_PRIM, gHC_PRIMOPWRAPPERS )
    
    126 128
     import GHC.Types.Name
    
    ... ... @@ -232,8 +234,13 @@ withInterp :: ExceptionMonad m => SafeInterp -> (Interp -> m a) -> m a
    232 234
     withInterp interp0@(SafeInterp interp) k = stopInterpOnPipeClosed $ k interp
    
    233 235
       where
    
    234 236
         stopInterpOnPipeClosed = MC.handle $ \ (e :: PipeClosedException) -> do
    
    235
    -      liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0
    
    236
    -      MC.throwM e
    
    237
    +      mec <- liftIO $ stopInterpWhen (atomically . fmap not . isPipeOpen . interpPipe) interp0
    
    238
    +      maybe (MC.throwM e) (liftIO . throwInterpreterTerminated . Just) mec
    
    239
    +
    
    240
    +throwInterpreterTerminated :: Maybe ExitCode -> IO a
    
    241
    +throwInterpreterTerminated ec = do
    
    242
    +  throwIO $ InstallationError $ "External interpreter terminated"
    
    243
    +          ++ case ec of Just (ExitFailure n) -> " (" ++ show n ++ ")"; _ -> ""
    
    237 244
     
    
    238 245
     withExtInterp :: ExceptionMonad m => ExtInterp -> (forall d. ExtInterpInstance d -> m a) -> m a
    
    239 246
     withExtInterp ext action = case ext of
    
    ... ... @@ -281,6 +288,7 @@ spawnInterpMaybe cfg spawn mstatus = do
    281 288
         -- readMVar first, so when the interp is running we don't take lock.
    
    282 289
         -- Removes an interruptible point for concurrent calls.
    
    283 290
         readMVar mstatus >>= \case
    
    291
    +      InterpStopped ec   -> throwInterpreterTerminated =<< liftIO (readIORef ec)
    
    284 292
           InterpRunning inst -> pure inst
    
    285 293
           InterpPending{}    -> modifyMVarMasked mstatus $ \case
    
    286 294
             -- start the external iserv process if we haven't done so yet
    
    ... ... @@ -290,6 +298,7 @@ spawnInterpMaybe cfg spawn mstatus = do
    290 298
     
    
    291 299
             InterpRunning inst -> do
    
    292 300
               pure (InterpRunning inst, inst)
    
    301
    +        InterpStopped ec -> throwInterpreterTerminated =<< liftIO (readIORef ec)
    
    293 302
     
    
    294 303
       -- free any ForeignRef that have been garbage collected.
    
    295 304
       -- or any other pending RemoteResource.
    
    ... ... @@ -310,8 +319,9 @@ withExtInterpMaybe
    310 319
       => ExtInterp -> (forall d. Maybe (ExtInterpInstance d) -> m a) -> m a
    
    311 320
     withExtInterpMaybe ext action = withExtInterpStatus ext $ \mstate -> do
    
    312 321
       liftIO (readMVar mstate) >>= \case
    
    313
    -    InterpPending {}   -> action Nothing -- already shut down or never launched
    
    322
    +    InterpPending {}   -> action Nothing
    
    314 323
         InterpRunning inst -> action (Just inst)
    
    324
    +    InterpStopped {}   -> action Nothing
    
    315 325
     
    
    316 326
     -- -----------------------------------------------------------------------------
    
    317 327
     -- Wrappers around messages
    
    ... ... @@ -674,38 +684,47 @@ spawnIServ conf = do
    674 684
       pure inst
    
    675 685
     
    
    676 686
     -- | Stop the interpreter
    
    677
    -stopInterp :: SafeInterp -> IO ()
    
    687
    +stopInterp :: SafeInterp -> IO (Maybe ExitCode)
    
    678 688
     stopInterp = stopInterpWhen (const $ pure True)
    
    679 689
     
    
    680 690
     -- | Stop the interpreter if predicate returns 'True'.
    
    681
    -stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO ()
    
    691
    +stopInterpWhen :: (InterpProcess -> IO Bool) -> SafeInterp -> IO (Maybe ExitCode)
    
    682 692
     stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of
    
    683 693
     #if defined(HAVE_INTERNAL_INTERPRETER)
    
    684
    -    InternalInterp -> pure ()
    
    694
    +    InternalInterp -> pure Nothing
    
    685 695
     #endif
    
    686
    -    ExternalInterp ext -> (maybe (pure ()) throwIO =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
    
    696
    +    ExternalInterp ext -> (either throwIO pure =<<) $ withExtInterpStatus ext $ \mstate -> MC.mask $ \restore -> do
    
    687 697
           -- takes interpLoader lock before ExternalInterp lock to avoid deadlocks.
    
    688 698
           -- commits emptied values before 'gracefulShutdown' so we don't hold locks
    
    689 699
           -- more than necessary.
    
    690 700
           mi <- modifyMVar (loader_state (interpLoader interp)) $ \l_st -> do
    
    691 701
            modifyMVar mstate $ \state -> do
    
    692 702
             case state of
    
    693
    -          InterpPending    -> pure (state, (l_st, Nothing)) -- already stopped
    
    703
    +          InterpStopped{}  -> pure (state, (l_st, Nothing)) -- already stopped
    
    704
    +          InterpPending    -> newIORef Nothing >>= \ec -> pure (InterpStopped ec, (l_st, Nothing))
    
    694 705
               InterpRunning i  -> shouldStop (instProcess i) >>= \case
    
    695 706
                 False -> pure (state, (l_st, Nothing))
    
    696 707
                 True  -> do
    
    697 708
                   purgeInterpSymbolCache (interpSymbolCache interp)
    
    698 709
                   modifyMVar_ (interpStringCache interp) (const $ pure emptyFsEnv)
    
    699
    -              pure (InterpPending,(Nothing,Just i))
    
    710
    +              ec <- newIORef Nothing
    
    711
    +              pure (InterpStopped ec,(Nothing,Just (i,ec)))
    
    700 712
           case mi of
    
    701
    -        Nothing -> pure Nothing
    
    702
    -        Just i  -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
    
    703
    -          Just _exitCode -> closePipe (interpPipe (instProcess i)) >> pure Nothing
    
    704
    -          Nothing        -> gracefulShutdown i restore
    
    713
    +        Nothing -> pure $ Right Nothing
    
    714
    +        Just (i,ecRef) -> getProcessExitCode (interpHandle (instProcess i)) >>= \case
    
    715
    +          Just exitCode -> do
    
    716
    +            writeExitCode ecRef (Just exitCode)
    
    717
    +            closePipe (interpPipe (instProcess i))
    
    718
    +            pure (Right $ Just exitCode)
    
    719
    +          Nothing       -> gracefulShutdown i ecRef restore
    
    705 720
     
    
    706 721
       where
    
    707
    -    gracefulShutdown i restore = do
    
    722
    +    writeExitCode _ref Nothing = pure ()
    
    723
    +    writeExitCode ref (Just ec) = atomicWriteIORef ref (Just ec)
    
    724
    +    gracefulShutdown :: ExtInterpInstance c -> IORef (Maybe ExitCode) -> (forall a. IO a -> IO a) -> IO (Either SomeException (Maybe ExitCode))
    
    725
    +    gracefulShutdown i ecRef restore = do
    
    708 726
           x <- try (liftM2 (>>) (timeLimited restore (sendMessage i Shutdown)) (timeLimited restore (closePipe (interpPipe (instProcess i)))))
    
    727
    +      print x
    
    709 728
           let ph = interpHandle (instProcess i)
    
    710 729
           e <- case x of
    
    711 730
             -- happy path: ext. interp. should be shutting down of its own accord.
    
    ... ... @@ -718,8 +737,9 @@ stopInterpWhen shouldStop (SafeInterp interp) = case interpInstance interp of
    718 737
             Left e -> do
    
    719 738
               terminateProcess ph
    
    720 739
               returnUnexpectedException e
    
    721
    -      void $ timeLimited restore $ void $ waitForProcess ph
    
    722
    -      pure e
    
    740
    +      mexitCode <- timeLimited restore $ waitForProcess ph
    
    741
    +      writeExitCode ecRef mexitCode
    
    742
    +      pure $ maybe (Right mexitCode) Left e
    
    723 743
         timeLimited restore m = timeout 1_000_000 (restore m)
    
    724 744
         returnUnexpectedException e
    
    725 745
           | Just (_ :: PipeClosedException) <- fromException e = return Nothing
    

  • compiler/GHC/Runtime/Interpreter/Types.hs
    ... ... @@ -64,6 +64,8 @@ import GHC.StgToJS.Linker.Types
    64 64
     import GHC.Runtime.Interpreter.Types.SymbolCache
    
    65 65
     
    
    66 66
     import Control.Concurrent
    
    67
    +import Data.IORef
    
    68
    +import System.Exit
    
    67 69
     import System.Process   ( ProcessHandle, CreateProcess )
    
    68 70
     import System.IO
    
    69 71
     import GHC.Unit.Finder.Types (FinderCache, FinderOpts)
    
    ... ... @@ -153,6 +155,7 @@ data InterpProcess = InterpProcess
    153 155
     data InterpStatus inst
    
    154 156
        = InterpPending       -- ^ Not spawned yet
    
    155 157
        | InterpRunning !inst -- ^ Running
    
    158
    +   | InterpStopped !(IORef (Maybe ExitCode)) -- ^ Died already.
    
    156 159
     
    
    157 160
     -- | Configuration needed to spawn an external interpreter
    
    158 161
     data IServConfig = IServConfig
    

  • libraries/ghci/GHCi/Message/Async.hs
    ... ... @@ -160,8 +160,8 @@ mkPipeFromContinuations getSome putAll pipeCloseRead pipeCloseWrite = mdo
    160 160
     -- too.
    
    161 161
     closePipe :: Pipe -> IO ()
    
    162 162
     closePipe Pipe{..} = do
    
    163
    -  throwTo (asyncFillTid pipeAsyncMngr) PipeWriteClosedException
    
    164
    -    `finally` throwTo (asyncDrainTid pipeAsyncMngr) PipeReadClosedException
    
    163
    +  throwTo (asyncFillTid pipeAsyncMngr) (PipeWriteClosedException Nothing)
    
    164
    +    `finally` throwTo (asyncDrainTid pipeAsyncMngr) (PipeReadClosedException Nothing)
    
    165 165
     
    
    166 166
     isPipeOpen :: Pipe -> STM Bool
    
    167 167
     isPipeOpen pipe = liftM2 (&&)
    
    ... ... @@ -190,12 +190,11 @@ closingPipe p = atomically $ do
    190 190
     
    
    191 191
     -- | Exception thrown/reported when attempting to read or write on a closed pipe.
    
    192 192
     --
    
    193
    --- Errors occurring while reading or writing will show up as the original
    
    194
    --- exception instead (e.g. IOException).
    
    193
    +-- Errors occurring while reading or writing are wrapped with this.
    
    195 194
     data PipeClosedException
    
    196
    -  = PipeReadClosedException  -- ^ We've closed the pipe read end on this process
    
    195
    +  = PipeReadClosedException {inner :: Maybe SomeException} -- ^ We've closed the pipe read end on this process
    
    197 196
     
    
    198
    -  | PipeWriteClosedException -- ^ We've closed the pipe write end on this process
    
    197
    +  | PipeWriteClosedException {inner :: Maybe SomeException} -- ^ We've closed the pipe write end on this process
    
    199 198
       deriving Show
    
    200 199
     instance Exception PipeClosedException
    
    201 200
     
    
    ... ... @@ -287,7 +286,7 @@ handleAsyncReq pipe getit mii k = mask $ \restore -> do
    287 286
       (uq,bs) <- atomically $ do
    
    288 287
         readTVar (pipeWriteStatus pipe) >>= \ s -> case isActive s of
    
    289 288
           -- We will not be able to write the reply, so no point in continuiting.
    
    290
    -      False -> throwSTM PipeWriteClosedException
    
    289
    +      False -> throwSTM $ PipeWriteClosedException Nothing
    
    291 290
           True  -> pure ()
    
    292 291
         taken <- case mii of
    
    293 292
           Nothing -> tryReadTQueue  $  requestsQueue am
    
    ... ... @@ -295,7 +294,7 @@ handleAsyncReq pipe getit mii k = mask $ \restore -> do
    295 294
         case taken of
    
    296 295
           Just req            -> pure req
    
    297 296
           Nothing  -> isActive <$> readTVar (pipeReadStatus pipe) >>= \case
    
    298
    -        False -> throwSTM PipeReadClosedException -- can't expect reqs
    
    297
    +        False -> throwSTM $ PipeReadClosedException Nothing -- can't expect reqs
    
    299 298
             True  -> retry
    
    300 299
     
    
    301 300
       let
    
    ... ... @@ -364,9 +363,9 @@ remoteAsyncReqWithResponse pipe msg ii = do
    364 363
       wv <- newEmptyTMVarIO
    
    365 364
     
    
    366 365
       atomically $ readTVar (pipeReadStatus pipe) >>= \ readEnd -> case isActive readEnd of
    
    367
    -    False  -> pure $ NotWritten PipeReadClosedException
    
    366
    +    False  -> pure $ NotWritten $ PipeReadClosedException Nothing
    
    368 367
         True -> writePipeAsync pipe (Request uq ii (runPut msg)) >>= \case
    
    369
    -      Nothing -> pure $ NotWritten PipeWriteClosedException
    
    368
    +      Nothing -> pure $ NotWritten $ PipeWriteClosedException Nothing
    
    370 369
           Just waitWritten -> do
    
    371 370
             -- request queued, so we register a pending reply. After this tx we
    
    372 371
             -- always expect a reply, and when it arrives 'drainPipe' will clean up 'pendingReplies'.
    
    ... ... @@ -562,7 +561,7 @@ newAsyncManager pipe = do
    562 561
     --
    
    563 562
     -- Closes the Pipe read end when done reading
    
    564 563
     drainPipe :: Pipe -> (forall x. IO x -> IO x) -> IO ()
    
    565
    -drainPipe p unmask = catch loop (void . replyToPendings) where
    
    564
    +drainPipe p unmask = catch loop (void . replyToPendings . toException . PipeReadClosedException . Just) where
    
    566 565
       loop = do
    
    567 566
         unmask (readPipe p) >>= \case
    
    568 567
           Just msg -> do
    
    ... ... @@ -571,7 +570,7 @@ drainPipe p unmask = catch loop (void . replyToPendings) where
    571 570
           -- EOF on read handle
    
    572 571
           Nothing -> do
    
    573 572
             -- exit loop
    
    574
    -        throwIO PipeReadClosedException
    
    573
    +        throwIO $ PipeReadClosedException Nothing
    
    575 574
       handleMsg = \case
    
    576 575
         -- Receive a reply to a pending notification
    
    577 576
         Reply uq bs -> do
    
    ... ... @@ -676,9 +675,9 @@ fillPipe p unmask = loop `catch` cleanup Nothing where
    676 675
             Nothing -> pure ()
    
    677 676
             Just var -> do
    
    678 677
               -- report exception to the originating write
    
    679
    -          putTMVar var . Left $ if isOpen s then e0 else toException PipeWriteClosedException
    
    678
    +          putTMVar var . Left . toException $ PipeWriteClosedException $ if isOpen s then Just e0 else Nothing
    
    680 679
           -- real exception already reported once
    
    681
    -      failPendingWrites p $ toException PipeWriteClosedException
    
    680
    +      failPendingWrites p $ toException $ PipeWriteClosedException Nothing
    
    682 681
     
    
    683 682
     failPendingWrites :: Pipe -> SomeException -> STM ()
    
    684 683
     failPendingWrites p e = do
    
    ... ... @@ -714,7 +713,7 @@ data ReplyResult
    714 713
     
    
    715 714
     replyResultMaybeThrow :: ReplyResult -> IO ()
    
    716 715
     replyResultMaybeThrow = \case
    
    717
    -  ReplyNotWritten -> throwIO PipeWriteClosedException
    
    716
    +  ReplyNotWritten -> throwIO $ PipeWriteClosedException Nothing
    
    718 717
       ReplyWritingError e -> throwIO e
    
    719 718
       ReplyWritingSuccess -> pure ()
    
    720 719
     
    

  • libraries/ghci/GHCi/Server.hs
    ... ... @@ -105,7 +105,8 @@ servWithCustom verbose hook pipe restore customHandler = do
    105 105
           -- reported as a different exception type.
    
    106 106
           ignorePipeClosedException = \case
    
    107 107
             ReplyWritingError e
    
    108
    -          | Just _ <- fromException @PipeClosedException e
    
    108
    +          | Just e' <- fromException @PipeClosedException e
    
    109
    +          , Nothing <- inner e'
    
    109 110
               -> pure ()
    
    110 111
               | otherwise
    
    111 112
               -> throwIO e