17

I'd like to implement a 'graceful shutdown' command for my webapp (as opposed to my first instinct, which is to just ask people to kill the process)

My first two attempts consisted of

  1. liftIO exitSuccess
  2. E.yield (responseLBS statusOK [G.contentType "text/plain"] "") E.EOF

Both of which just cheerfully returned a result to the client and continued listening. Is there anything an application can do to kill the server? Is this even a reasonable thing to want to do?

I confess I don't have a very strong understanding of iteratee, only enough to know that I can consume my input and that Iteratee is a MonadIO instance.

hammar
  • 138,522
  • 17
  • 304
  • 385
kowey
  • 1,211
  • 7
  • 15
  • 3
    Squinting at https://groups.google.com/forum/#!topic/yesodweb/VoenrabRUBQ , one trick that *seems* to work for me is to use Concurrent Haskell: (1) fork the run application (2) wait on an MVar and (3) when I'm ready to stop, just put something into that MVar... – kowey Oct 24 '11 at 20:51
  • 3
    That's what I'd recommend as well. – Michael Snoyman Oct 25 '11 at 03:22

1 Answers1

13
  1. Use an MVar. Block the main thread until the MVar has been signaled, then cleanup and exit.
  2. Call exitImmediately. One of the fastest ways to tear down the process, and also terribly annoying to debug. I don't believe finalizers/brackets/finally blocks will be called on the way down, depending on your application it may corrupt state.
  3. Throw an exception to the main thread. Warp.run doesn't catch exceptions, so this works by allowing the default exception handler on the main thread (and the main thread only) to terminate the process.

As others have mentioned, using an MVar is probably the best option. I included the others for the sake of completeness, but they do have their place. throwTo is used somewhat in the base library and I've worked on a few applications that use the C equivalent of exitImmediately: exit(), though I haven't run across any Haskell apps that use this method.

{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Control.Concurrent (MVar, ThreadId, forkIO, myThreadId, newEmptyMVar, putMVar, takeMVar)
import Control.Exception (Exception, throwTo)
import Control.Monad.Trans (liftIO)
import Data.ByteString (ByteString)
import Data.Data (Data, Typeable)
import Data.Enumerator (Iteratee)
import Network.HTTP.Types
import Network.Wai as Wai
import Network.Wai.Handler.Warp as Warp
import System.Exit (ExitCode (ExitSuccess))
import System.Posix.Process (exitImmediately)

data Shutdown = Shutdown deriving (Data, Typeable, Show)
instance Exception Shutdown

app :: ThreadId -> MVar () -> Request -> Iteratee ByteString IO Response
app mainThread shutdownMVar Request{pathInfo = pathInfo} = do
  liftIO $ case pathInfo of
    ["shutdownByThrowing"] -> throwTo mainThread Shutdown
    ["shutdownByMVar"]     -> putMVar shutdownMVar ()
    ["shutdownByExit"]     -> exitImmediately ExitSuccess
    _                      -> return ()
  return $ responseLBS statusOK [headerContentType "text/plain"] "ok"

main :: IO ()
main = do
  mainThread <- myThreadId
  shutdownMVar <- newEmptyMVar
  forkIO $ Warp.run 3000 (app mainThread shutdownMVar)
  takeMVar shutdownMVar 
Nathan Howell
  • 4,627
  • 1
  • 22
  • 30
  • Thanks for covering all possibilities. I agree that comprehensiveness is useful, if nothing else, to get a better idea how Warp works. I ended up taking the shutdownByMVar route, so will accept your answer – kowey Nov 21 '11 at 10:22
  • Hm.. I've tried that MVar approach and the server indeed stops. However, the shutdown was not "graceful" - the remaining requests were killed off. – wiz Apr 22 '13 at 11:35
  • 1
    @wiz Yes, it exits immediately. Implementing a graceful shutdown isn't much more involved, I've uploaded an *untested* sample here: https://gist.github.com/NathanHowell/5435345 – Nathan Howell Apr 22 '13 at 14:03
  • @wiz Changing it is simple... your handler just need to check if a shutdown is in progress and return a 503 in that case. I've updated the sample again anyways. – Nathan Howell Apr 24 '13 at 14:49
  • I wonder if the server itself could/should do things like this i.e. stop accepting new connections and let other finish... – wiz Apr 25 '13 at 09:10
  • also, if you "stop" it using the MVar method under ghci, the WAI keeps running inside the ghci process, having leaked its way into the background – clever Jul 10 '17 at 20:00