-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimeout.hs
More file actions
232 lines (202 loc) · 7.39 KB
/
timeout.hs
File metadata and controls
232 lines (202 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent (MVar, forkIO, newEmptyMVar, putMVar, threadDelay, tryTakeMVar)
import Control.Exception (SomeException, catch)
import Control.Monad (when)
import System.Console.GetOpt
import System.Environment (getArgs, getProgName)
import System.Exit (ExitCode (..), exitWith)
import System.IO (hPutStrLn, stderr)
import System.IO.Error (isDoesNotExistError, isPermissionError)
import System.Posix.Signals (Signal, sigHUP, sigINT, sigKILL, sigTERM, sigUSR1, sigUSR2, signalProcess)
import System.Posix.Types (CPid)
import System.Process (CreateProcess (..), ProcessHandle, StdStream (..), createProcess, getPid, getProcessExitCode, proc, std_err, std_in, std_out, waitForProcess)
exitTimeout :: Int
exitTimeout = 124
exitTimeoutFailure :: Int
exitTimeoutFailure = 125
exitCommandNotExecutable :: Int
exitCommandNotExecutable = 126
exitCommandNotFound :: Int
exitCommandNotFound = 127
exitKilledByKillSignal :: Int
exitKilledByKillSignal = 137
data TimeoutOptions = TimeoutOptions
{ foreground :: Bool,
killAfter :: Maybe String,
preserveStatus :: Bool,
signal :: Maybe String,
verbose :: Bool,
help :: Bool,
version :: Bool
}
deriving (Show)
defaultOptions :: TimeoutOptions
defaultOptions =
TimeoutOptions
{ foreground = False,
killAfter = Nothing,
preserveStatus = False,
signal = Nothing,
verbose = False,
help = False,
version = False
}
options :: [OptDescr (TimeoutOptions -> TimeoutOptions)]
options =
[ Option
['f']
["foreground"]
(NoArg (\opts -> opts {foreground = True}))
"allow COMMAND to read from TTY and get TTY signals",
Option
['k']
["kill-after"]
(ReqArg (\dur opts -> opts {killAfter = Just dur}) "DURATION")
"also send KILL signal after DURATION",
Option
['p']
["preserve-status"]
(NoArg (\opts -> opts {preserveStatus = True}))
"exit with same status as COMMAND",
Option
['s']
["signal"]
(ReqArg (\sig opts -> opts {signal = Just sig}) "SIGNAL")
"specify signal to send on timeout",
Option
['v']
["verbose"]
(NoArg (\opts -> opts {verbose = True}))
"diagnose to stderr any signal sent",
Option
[]
["help"]
(NoArg (\opts -> opts {help = True}))
"display this help and exit",
Option
[]
["version"]
(NoArg (\opts -> opts {version = True}))
"output version information and exit"
]
parseArgs :: [String] -> IO (TimeoutOptions, String, String, [String])
parseArgs argv =
let helpMsg = "\nTry '--help' for more information."
in case getOpt RequireOrder options argv of
(o, n, []) -> do
let opts = foldl (flip id) defaultOptions o
if opts.help || opts.version
then return (opts, "", "", [])
else case n of
[] -> error $ "missing operand" ++ helpMsg
[_] -> error $ "missing command" ++ helpMsg
duration : cmd : args -> return (opts, duration, cmd, args)
(_, _, errs) -> error (concat errs ++ helpMsg)
showHelp :: IO ()
showHelp = do
progName <- getProgName
let header = "Usage: " ++ progName ++ " [OPTION] DURATION COMMAND [ARG]..."
putStrLn (usageInfo header options)
showVersion :: IO ()
showVersion = putStrLn "timeout (Haskell implementation) 0.1.0"
parseDuration :: String -> IO Int
parseDuration s = case reads s of
[(n :: Double, "ms")] -> return (round (n * 1000))
[(n :: Double, "s")] -> return (round (n * 1000000))
[(n :: Double, "m")] -> return (round (n * 60000000))
[(n :: Double, "h")] -> return (round (n * 3600000000))
[(n :: Double, "d")] -> return (round (n * 86400000000))
[(n :: Double, "")] -> return (round (n * 1000000))
_ -> error $ "invalid time interval: '" ++ s ++ "'\nTry '--help' for more information."
parseSignal :: String -> Signal
parseSignal "TERM" = sigTERM
parseSignal "KILL" = sigKILL
parseSignal "INT" = sigINT
parseSignal "HUP" = sigHUP
parseSignal "USR1" = sigUSR1
parseSignal "USR2" = sigUSR2
parseSignal s = case reads s of
[(n :: Int, "")] -> fromIntegral n
_ -> error $ "invalid signal: '" ++ s ++ "'\nTry '--help' for more information."
getProcessId :: ProcessHandle -> IO CPid
getProcessId ph = do
mpid <- getPid ph
case mpid of
Just pid -> return pid
Nothing -> error "Failed to get process ID"
determineSignal :: TimeoutOptions -> Signal
determineSignal opts = maybe sigTERM parseSignal opts.signal
buildProcessConfig :: TimeoutOptions -> String -> [String] -> CreateProcess
buildProcessConfig opts cmd cmdArgs =
if opts.foreground
then (proc cmd cmdArgs) {std_in = Inherit, std_out = Inherit, std_err = Inherit}
else proc cmd cmdArgs
startProcess :: CreateProcess -> IO ProcessHandle
startProcess processConfig = do
(_, _, _, ph) <- createProcess processConfig
return ph
startTimeoutThread :: Int -> Maybe Int -> TimeoutOptions -> CPid -> ProcessHandle -> MVar Bool -> IO ()
startTimeoutThread micros killMicros opts pid ph timeoutOccurred = do
let signal = determineSignal opts
_ <- forkIO $ do
threadDelay micros
putMVar timeoutOccurred True
when opts.verbose $ hPutStrLn stderr $ "sending signal " ++ show signal ++ " to process " ++ show pid
signalProcess signal pid `catch` \(_ :: SomeException) -> return ()
case killMicros of
Just killDelay -> do
threadDelay killDelay
mExitCode <- getProcessExitCode ph
case mExitCode of
Nothing -> do
when opts.verbose $ hPutStrLn stderr $ "sending signal KILL to process " ++ show pid
signalProcess sigKILL pid `catch` \(_ :: SomeException) -> return ()
Just _ -> return ()
Nothing -> return ()
return ()
handleExitCode :: TimeoutOptions -> Maybe Bool -> ExitCode -> ExitCode
handleExitCode opts timeoutHappened exitCode = case (timeoutHappened, exitCode) of
(Just True, _) ->
if opts.preserveStatus
then exitCode
else ExitFailure exitTimeout
(_, ExitSuccess) -> ExitSuccess
(_, ExitFailure code) -> ExitFailure code
runTimeout :: TimeoutOptions -> String -> String -> [String] -> IO ExitCode
runTimeout opts duration cmd cmdArgs =
do
micros <- parseDuration duration
killMicros <- maybe (return Nothing) (fmap Just . parseDuration) opts.killAfter
let processConfig = buildProcessConfig opts cmd cmdArgs
ph <- startProcess processConfig
pid <- getProcessId ph
timeoutOccurred <- newEmptyMVar
startTimeoutThread micros killMicros opts pid ph timeoutOccurred
exitCode <- waitForProcess ph
timeoutHappened <- tryTakeMVar timeoutOccurred
return $ handleExitCode opts timeoutHappened exitCode
`catch` \(e :: IOError) -> do
if isDoesNotExistError e
then return $ ExitFailure exitCommandNotFound
else
if isPermissionError e
then return $ ExitFailure exitCommandNotExecutable
else return $ ExitFailure exitTimeoutFailure
run :: IO ExitCode
run = do
args <- getArgs
(opts, duration, cmd, cmdArgs) <- parseArgs args
case () of
_
| opts.help -> showHelp >> return ExitSuccess
| opts.version -> showVersion >> return ExitSuccess
| otherwise -> runTimeout opts duration cmd cmdArgs
main :: IO ()
main = do
exitCode <-
run `catch` \e -> do
hPutStrLn stderr (show (e :: SomeException))
return (ExitFailure exitTimeoutFailure)
exitWith exitCode