Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Utils.hs @ 79eef90b

History | View | Annotate | Download (7.9 kB)

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
  , 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
-- | Return the first result with a True condition, or the default otherwise.
136
select :: a            -- ^ default result
137
       -> [(Bool, a)]  -- ^ list of \"condition, result\"
138
       -> a            -- ^ first result which has a True condition, or default
139
select def = maybe def snd . find fst
140

    
141

    
142
-- * Parsing utility functions
143

    
144
-- | Parse results from readsPrec.
145
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
146
parseChoices _ _ ((v, ""):[]) = return v
147
parseChoices name s ((_, e):[]) =
148
    fail $ name ++ ": leftover characters when parsing '"
149
           ++ s ++ "': '" ++ e ++ "'"
150
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
151

    
152
-- | Safe 'read' function returning data encapsulated in a Result.
153
tryRead :: (Monad m, Read a) => String -> String -> m a
154
tryRead name s = parseChoices name s $ reads s
155

    
156
-- | Format a table of strings to maintain consistent length.
157
formatTable :: [[String]] -> [Bool] -> [[String]]
158
formatTable vals numpos =
159
    let vtrans = transpose vals  -- transpose, so that we work on rows
160
                                 -- rather than columns
161
        mlens = map (maximum . map length) vtrans
162
        expnd = map (\(flds, isnum, ml) ->
163
                         map (\val ->
164
                                  let delta = ml - length val
165
                                      filler = replicate delta ' '
166
                                  in if delta > 0
167
                                     then if isnum
168
                                          then filler ++ val
169
                                          else val ++ filler
170
                                     else val
171
                             ) flds
172
                    ) (zip3 vtrans numpos mlens)
173
   in transpose expnd
174

    
175
-- | Constructs a printable table from given header and rows
176
printTable :: String -> [String] -> [[String]] -> [Bool] -> String
177
printTable lp header rows isnum =
178
  unlines . map ((++) lp) . map ((:) ' ' . unwords) $
179
  formatTable (header:rows) isnum
180

    
181
-- | Converts a unit (e.g. m or GB) into a scaling factor.
182
parseUnitValue :: (Monad m) => String -> m Rational
183
parseUnitValue unit
184
  -- binary conversions first
185
  | null unit                     = return 1
186
  | unit == "m" || upper == "MIB" = return 1
187
  | unit == "g" || upper == "GIB" = return kbBinary
188
  | unit == "t" || upper == "TIB" = return $ kbBinary * kbBinary
189
  -- SI conversions
190
  | unit == "M" || upper == "MB"  = return mbFactor
191
  | unit == "G" || upper == "GB"  = return $ mbFactor * kbDecimal
192
  | unit == "T" || upper == "TB"  = return $ mbFactor * kbDecimal * kbDecimal
193
  | otherwise = fail $ "Unknown unit '" ++ unit ++ "'"
194
  where upper = map toUpper unit
195
        kbBinary = 1024 :: Rational
196
        kbDecimal = 1000 :: Rational
197
        decToBin = kbDecimal / kbBinary -- factor for 1K conversion
198
        mbFactor = decToBin * decToBin -- twice the factor for just 1K
199

    
200
-- | Tries to extract number and scale from the given string.
201
--
202
-- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is
203
-- specified, it defaults to MiB. Return value is always an integral
204
-- value in MiB.
205
parseUnit :: (Monad m, Integral a, Read a) => String -> m a
206
parseUnit str =
207
  -- TODO: enhance this by splitting the unit parsing code out and
208
  -- accepting floating-point numbers
209
  case (reads str::[(Int, String)]) of
210
    [(v, suffix)] ->
211
      let unit = dropWhile (== ' ') suffix
212
      in do
213
        scaling <- parseUnitValue unit
214
        return $ truncate (fromIntegral v * scaling)
215
    _ -> fail $ "Can't parse string '" ++ str ++ "'"
216

    
217
-- | Unwraps a 'Result', exiting the program if it is a 'Bad' value,
218
-- otherwise returning the actual contained value.
219
exitIfBad :: String -> Result a -> IO a
220
exitIfBad msg (Bad s) = do
221
  hPutStrLn stderr $ "Error: " ++ msg ++ ": " ++ s
222
  exitWith (ExitFailure 1)
223
exitIfBad _ (Ok v) = return v
224

    
225
-- | Exits immediately with an error message.
226
exitErr :: String -> IO a
227
exitErr errmsg = do
228
  hPutStrLn stderr $ "Error: " ++ errmsg ++ "."
229
  exitWith (ExitFailure 1)
230

    
231
-- | Exits with an error message if the given boolean condition if true.
232
exitWhen :: Bool -> String -> IO ()
233
exitWhen True msg = exitErr msg
234
exitWhen False _  = return ()
235

    
236
-- | Exits with an error message /unless/ the given boolean condition
237
-- if true, the opposite of 'exitWhen'.
238
exitUnless :: Bool -> String -> IO ()
239
exitUnless cond = exitWhen (not cond)