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
24 module Ganeti.HTools.Utils
45 import Data.Char (toUpper)
50 import Ganeti.BasicTypes
56 -- | To be used only for debugging, breaks referential integrity.
57 debug :: Show a => a -> a
58 debug x = trace (show x) x
60 -- | Displays a modified form of the second parameter before returning
62 debugFn :: Show b => (a -> b) -> a -> a
63 debugFn fn x = debug (fn x) `seq` x
65 -- | Show the first parameter before returning the second one.
66 debugXy :: Show a => a -> b -> b
71 -- | Apply the function if condition holds, otherwise use default value.
72 applyIf :: Bool -> (a -> a) -> a -> a
73 applyIf b f x = if b then f x else x
75 -- | Comma-join a string list.
76 commaJoin :: [String] -> String
77 commaJoin = intercalate ","
79 -- | Split a list on a separator and return an array.
80 sepSplit :: Eq a => a -> [a] -> [[a]]
85 | otherwise = x:sepSplit sep ys
86 where (x, xs) = break (== sep) s
89 -- | Simple pluralize helper
90 plural :: Int -> String -> String -> String
94 -- * Mathematical functions
96 -- Simple and slow statistical functions, please replace with better
99 -- | Standard deviation function.
100 stdDev :: [Double] -> Double
102 -- first, calculate the list length and sum lst in a single step,
103 -- for performance reasons
104 let (ll', sx) = foldl' (\(rl, rs) e ->
107 in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
108 ll = fromIntegral ll'::Double
110 av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
111 in sqrt (av / ll) -- stddev
113 -- * Logical functions
115 -- Avoid syntactic sugar and enhance readability. These functions are proposed
116 -- by some for inclusion in the Prelude, and at the moment they are present
117 -- (with various definitions) in the utility-ht package. Some rationale and
118 -- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else>
120 -- | \"if\" as a function, rather than as syntactic sugar.
121 if' :: Bool -- ^ condition
122 -> a -- ^ \"then\" result
123 -> a -- ^ \"else\" result
124 -> a -- ^ \"then\" or "else" result depending on the condition
128 -- | Return the first result with a True condition, or the default otherwise.
129 select :: a -- ^ default result
130 -> [(Bool, a)] -- ^ list of \"condition, result\"
131 -> a -- ^ first result which has a True condition, or default
132 select def = maybe def snd . find fst
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) . map ((:) ' ' . 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)