Rename Ganeti/HTools/Utils.hs to Ganeti/Utils.hs
[ganeti-local] / htools / Ganeti / Utils.hs
1 {-| Utility functions. -}
2
3 {-
4
5 Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
6
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.
11
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.
16
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
20 02110-1301, USA.
21
22 -}
23
24 module Ganeti.Utils
25   ( debug
26   , debugFn
27   , debugXy
28   , sepSplit
29   , stdDev
30   , if'
31   , select
32   , applyIf
33   , commaJoin
34   , ensureQuoted
35   , tryRead
36   , formatTable
37   , printTable
38   , parseUnit
39   , plural
40   , exitIfBad
41   , exitErr
42   , exitWhen
43   , exitUnless
44   ) where
45
46 import Data.Char (toUpper, isAlphaNum)
47 import Data.List
48
49 import Debug.Trace
50
51 import Ganeti.BasicTypes
52 import System.IO
53 import System.Exit
54
55 -- * Debug functions
56
57 -- | To be used only for debugging, breaks referential integrity.
58 debug :: Show a => a -> a
59 debug x = trace (show x) x
60
61 -- | Displays a modified form of the second parameter before returning
62 -- it.
63 debugFn :: Show b => (a -> b) -> a -> a
64 debugFn fn x = debug (fn x) `seq` x
65
66 -- | Show the first parameter before returning the second one.
67 debugXy :: Show a => a -> b -> b
68 debugXy = seq . debug
69
70 -- * Miscellaneous
71
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
75
76 -- | Comma-join a string list.
77 commaJoin :: [String] -> String
78 commaJoin = intercalate ","
79
80 -- | Split a list on a separator and return an array.
81 sepSplit :: Eq a => a -> [a] -> [[a]]
82 sepSplit sep s
83   | null s    = []
84   | null xs   = [x]
85   | null ys   = [x,[]]
86   | otherwise = x:sepSplit sep ys
87   where (x, xs) = break (== sep) s
88         ys = drop 1 xs
89
90 -- | Simple pluralize helper
91 plural :: Int -> String -> String -> String
92 plural 1 s _ = s
93 plural _ _ p = p
94
95 -- | Ensure a value is quoted if needed.
96 ensureQuoted :: String -> String
97 ensureQuoted v = if not (all (\c -> isAlphaNum c || c == '.') v)
98                  then '\'':v ++ "'"
99                  else v
100
101 -- * Mathematical functions
102
103 -- Simple and slow statistical functions, please replace with better
104 -- versions
105
106 -- | Standard deviation function.
107 stdDev :: [Double] -> Double
108 stdDev lst =
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 ->
112                            let rl' = rl + 1
113                                rs' = rs + e
114                            in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
115       ll = fromIntegral ll'::Double
116       mv = sx / ll
117       av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
118   in sqrt (av / ll) -- stddev
119
120 -- *  Logical functions
121
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>
126
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
132 if' True x _ = x
133 if' _    _ y = y
134
135 -- * Parsing utility functions
136
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 ++ "'"
144
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
148
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) ->
156                          map (\val ->
157                                   let delta = ml - length val
158                                       filler = replicate delta ' '
159                                   in if delta > 0
160                                      then if isnum
161                                           then filler ++ val
162                                           else val ++ filler
163                                      else val
164                              ) flds
165                     ) (zip3 vtrans numpos mlens)
166    in transpose expnd
167
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
173
174 -- | Converts a unit (e.g. m or GB) into a scaling factor.
175 parseUnitValue :: (Monad m) => String -> m Rational
176 parseUnitValue unit
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
182   -- SI conversions
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
192
193 -- | Tries to extract number and scale from the given string.
194 --
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
197 -- value in MiB.
198 parseUnit :: (Monad m, Integral a, Read a) => String -> m a
199 parseUnit str =
200   -- TODO: enhance this by splitting the unit parsing code out and
201   -- accepting floating-point numbers
202   case (reads str::[(Int, String)]) of
203     [(v, suffix)] ->
204       let unit = dropWhile (== ' ') suffix
205       in do
206         scaling <- parseUnitValue unit
207         return $ truncate (fromIntegral v * scaling)
208     _ -> fail $ "Can't parse string '" ++ str ++ "'"
209
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
217
218 -- | Exits immediately with an error message.
219 exitErr :: String -> IO a
220 exitErr errmsg = do
221   hPutStrLn stderr $ "Error: " ++ errmsg ++ "."
222   exitWith (ExitFailure 1)
223
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 ()
228
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)