1 {-| Utility functions. -}
5 Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
46 import Data.Char (toUpper, isAlphaNum)
51 import Ganeti.BasicTypes
57 -- | To be used only for debugging, breaks referential integrity.
58 debug :: Show a => a -> a
59 debug x = trace (show x) x
61 -- | Displays a modified form of the second parameter before returning
63 debugFn :: Show b => (a -> b) -> a -> a
64 debugFn fn x = debug (fn x) `seq` x
66 -- | Show the first parameter before returning the second one.
67 debugXy :: Show a => a -> b -> b
72 -- | Apply the function if condition holds, otherwise use default value.
73 applyIf :: Bool -> (a -> a) -> a -> a
74 applyIf b f x = if b then f x else x
76 -- | Comma-join a string list.
77 commaJoin :: [String] -> String
78 commaJoin = intercalate ","
80 -- | Split a list on a separator and return an array.
81 sepSplit :: Eq a => a -> [a] -> [[a]]
86 | otherwise = x:sepSplit sep ys
87 where (x, xs) = break (== sep) s
90 -- | Simple pluralize helper
91 plural :: Int -> String -> String -> String
95 -- | Ensure a value is quoted if needed.
96 ensureQuoted :: String -> String
97 ensureQuoted v = if not (all (\c -> isAlphaNum c || c == '.') v)
101 -- * Mathematical functions
103 -- Simple and slow statistical functions, please replace with better
106 -- | Standard deviation function.
107 stdDev :: [Double] -> Double
109 -- first, calculate the list length and sum lst in a single step,
110 -- for performance reasons
111 let (ll', sx) = foldl' (\(rl, rs) e ->
114 in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
115 ll = fromIntegral ll'::Double
117 av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
118 in sqrt (av / ll) -- stddev
120 -- * Logical functions
122 -- Avoid syntactic sugar and enhance readability. These functions are proposed
123 -- by some for inclusion in the Prelude, and at the moment they are present
124 -- (with various definitions) in the utility-ht package. Some rationale and
125 -- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else>
127 -- | \"if\" as a function, rather than as syntactic sugar.
128 if' :: Bool -- ^ condition
129 -> a -- ^ \"then\" result
130 -> a -- ^ \"else\" result
131 -> a -- ^ \"then\" or "else" result depending on the condition
135 -- * Parsing utility functions
137 -- | Parse results from readsPrec.
138 parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
139 parseChoices _ _ ((v, ""):[]) = return v
140 parseChoices name s ((_, e):[]) =
141 fail $ name ++ ": leftover characters when parsing '"
142 ++ s ++ "': '" ++ e ++ "'"
143 parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
145 -- | Safe 'read' function returning data encapsulated in a Result.
146 tryRead :: (Monad m, Read a) => String -> String -> m a
147 tryRead name s = parseChoices name s $ reads s
149 -- | Format a table of strings to maintain consistent length.
150 formatTable :: [[String]] -> [Bool] -> [[String]]
151 formatTable vals numpos =
152 let vtrans = transpose vals -- transpose, so that we work on rows
153 -- rather than columns
154 mlens = map (maximum . map length) vtrans
155 expnd = map (\(flds, isnum, ml) ->
157 let delta = ml - length val
158 filler = replicate delta ' '
165 ) (zip3 vtrans numpos mlens)
168 -- | Constructs a printable table from given header and rows
169 printTable :: String -> [String] -> [[String]] -> [Bool] -> String
170 printTable lp header rows isnum =
171 unlines . map ((++) lp . (:) ' ' . unwords) $
172 formatTable (header:rows) isnum
174 -- | Converts a unit (e.g. m or GB) into a scaling factor.
175 parseUnitValue :: (Monad m) => String -> m Rational
177 -- binary conversions first
178 | null unit = return 1
179 | unit == "m" || upper == "MIB" = return 1
180 | unit == "g" || upper == "GIB" = return kbBinary
181 | unit == "t" || upper == "TIB" = return $ kbBinary * kbBinary
183 | unit == "M" || upper == "MB" = return mbFactor
184 | unit == "G" || upper == "GB" = return $ mbFactor * kbDecimal
185 | unit == "T" || upper == "TB" = return $ mbFactor * kbDecimal * kbDecimal
186 | otherwise = fail $ "Unknown unit '" ++ unit ++ "'"
187 where upper = map toUpper unit
188 kbBinary = 1024 :: Rational
189 kbDecimal = 1000 :: Rational
190 decToBin = kbDecimal / kbBinary -- factor for 1K conversion
191 mbFactor = decToBin * decToBin -- twice the factor for just 1K
193 -- | Tries to extract number and scale from the given string.
195 -- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is
196 -- specified, it defaults to MiB. Return value is always an integral
198 parseUnit :: (Monad m, Integral a, Read a) => String -> m a
200 -- TODO: enhance this by splitting the unit parsing code out and
201 -- accepting floating-point numbers
202 case (reads str::[(Int, String)]) of
204 let unit = dropWhile (== ' ') suffix
206 scaling <- parseUnitValue unit
207 return $ truncate (fromIntegral v * scaling)
208 _ -> fail $ "Can't parse string '" ++ str ++ "'"
210 -- | Unwraps a 'Result', exiting the program if it is a 'Bad' value,
211 -- otherwise returning the actual contained value.
212 exitIfBad :: String -> Result a -> IO a
213 exitIfBad msg (Bad s) = do
214 hPutStrLn stderr $ "Error: " ++ msg ++ ": " ++ s
215 exitWith (ExitFailure 1)
216 exitIfBad _ (Ok v) = return v
218 -- | Exits immediately with an error message.
219 exitErr :: String -> IO a
221 hPutStrLn stderr $ "Error: " ++ errmsg ++ "."
222 exitWith (ExitFailure 1)
224 -- | Exits with an error message if the given boolean condition if true.
225 exitWhen :: Bool -> String -> IO ()
226 exitWhen True msg = exitErr msg
227 exitWhen False _ = return ()
229 -- | Exits with an error message /unless/ the given boolean condition
230 -- if true, the opposite of 'exitWhen'.
231 exitUnless :: Bool -> String -> IO ()
232 exitUnless cond = exitWhen (not cond)