Fix prefix bug in Haskell ssconf implementation
[ganeti-local] / htools / Ganeti / HTools / 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.HTools.Utils
25   ( debug
26   , debugFn
27   , debugXy
28   , sepSplit
29   , stdDev
30   , if'
31   , select
32   , applyIf
33   , commaJoin
34   , tryRead
35   , formatTable
36   , printTable
37   , parseUnit
38   , plural
39   , exitIfBad
40   , exitErr
41   , exitWhen
42   , exitUnless
43   ) where
44
45 import Data.Char (toUpper)
46 import Data.List
47
48 import Debug.Trace
49
50 import Ganeti.BasicTypes
51 import System.IO
52 import System.Exit
53
54 -- * Debug functions
55
56 -- | To be used only for debugging, breaks referential integrity.
57 debug :: Show a => a -> a
58 debug x = trace (show x) x
59
60 -- | Displays a modified form of the second parameter before returning
61 -- it.
62 debugFn :: Show b => (a -> b) -> a -> a
63 debugFn fn x = debug (fn x) `seq` x
64
65 -- | Show the first parameter before returning the second one.
66 debugXy :: Show a => a -> b -> b
67 debugXy = seq . debug
68
69 -- * Miscellaneous
70
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
74
75 -- | Comma-join a string list.
76 commaJoin :: [String] -> String
77 commaJoin = intercalate ","
78
79 -- | Split a list on a separator and return an array.
80 sepSplit :: Eq a => a -> [a] -> [[a]]
81 sepSplit sep s
82   | null s    = []
83   | null xs   = [x]
84   | null ys   = [x,[]]
85   | otherwise = x:sepSplit sep ys
86   where (x, xs) = break (== sep) s
87         ys = drop 1 xs
88
89 -- | Simple pluralize helper
90 plural :: Int -> String -> String -> String
91 plural 1 s _ = s
92 plural _ _ p = p
93
94 -- * Mathematical functions
95
96 -- Simple and slow statistical functions, please replace with better
97 -- versions
98
99 -- | Standard deviation function.
100 stdDev :: [Double] -> Double
101 stdDev lst =
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 ->
105                            let rl' = rl + 1
106                                rs' = rs + e
107                            in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
108       ll = fromIntegral ll'::Double
109       mv = sx / ll
110       av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
111   in sqrt (av / ll) -- stddev
112
113 -- *  Logical functions
114
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>
119
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
125 if' True x _ = x
126 if' _    _ y = y
127
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
133
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) . map ((:) ' ' . 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)