Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Utils.hs @ 1cdcf8f3

History | View | Annotate | Download (6.7 kB)

1
{-| Utility functions. -}
2

    
3
{-
4

    
5
Copyright (C) 2009, 2010, 2011 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
  ) where
40

    
41
import Data.Char (toUpper)
42
import Data.List
43
import Data.Ratio ((%))
44

    
45
import Debug.Trace
46

    
47
-- * Debug functions
48

    
49
-- | To be used only for debugging, breaks referential integrity.
50
debug :: Show a => a -> a
51
debug x = trace (show x) x
52

    
53
-- | Displays a modified form of the second parameter before returning
54
-- it.
55
debugFn :: Show b => (a -> b) -> a -> a
56
debugFn fn x = debug (fn x) `seq` x
57

    
58
-- | Show the first parameter before returning the second one.
59
debugXy :: Show a => a -> b -> b
60
debugXy = seq . debug
61

    
62
-- * Miscellaneous
63

    
64
-- | Apply the function if condition holds, otherwise use default value.
65
applyIf :: Bool -> (a -> a) -> a -> a
66
applyIf b f x = if b then f x else x
67

    
68
-- | Comma-join a string list.
69
commaJoin :: [String] -> String
70
commaJoin = intercalate ","
71

    
72
-- | Split a list on a separator and return an array.
73
sepSplit :: Eq a => a -> [a] -> [[a]]
74
sepSplit sep s
75
  | null s    = []
76
  | null xs   = [x]
77
  | null ys   = [x,[]]
78
  | otherwise = x:sepSplit sep ys
79
  where (x, xs) = break (== sep) s
80
        ys = drop 1 xs
81

    
82
-- | Simple pluralize helper
83
plural :: Int -> String -> String -> String
84
plural 1 s _ = s
85
plural _ _ p = p
86

    
87
-- * Mathematical functions
88

    
89
-- Simple and slow statistical functions, please replace with better
90
-- versions
91

    
92
-- | Standard deviation function.
93
stdDev :: [Double] -> Double
94
stdDev lst =
95
  -- first, calculate the list length and sum lst in a single step,
96
  -- for performance reasons
97
  let (ll', sx) = foldl' (\(rl, rs) e ->
98
                           let rl' = rl + 1
99
                               rs' = rs + e
100
                           in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
101
      ll = fromIntegral ll'::Double
102
      mv = sx / ll
103
      av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
104
  in sqrt (av / ll) -- stddev
105

    
106
-- *  Logical functions
107

    
108
-- Avoid syntactic sugar and enhance readability. These functions are proposed
109
-- by some for inclusion in the Prelude, and at the moment they are present
110
-- (with various definitions) in the utility-ht package. Some rationale and
111
-- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else>
112

    
113
-- | \"if\" as a function, rather than as syntactic sugar.
114
if' :: Bool -- ^ condition
115
    -> a    -- ^ \"then\" result
116
    -> a    -- ^ \"else\" result
117
    -> a    -- ^ \"then\" or "else" result depending on the condition
118
if' True x _ = x
119
if' _    _ y = y
120

    
121
-- | Return the first result with a True condition, or the default otherwise.
122
select :: a            -- ^ default result
123
       -> [(Bool, a)]  -- ^ list of \"condition, result\"
124
       -> a            -- ^ first result which has a True condition, or default
125
select def = maybe def snd . find fst
126

    
127

    
128
-- * Parsing utility functions
129

    
130
-- | Parse results from readsPrec.
131
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
132
parseChoices _ _ ((v, ""):[]) = return v
133
parseChoices name s ((_, e):[]) =
134
    fail $ name ++ ": leftover characters when parsing '"
135
           ++ s ++ "': '" ++ e ++ "'"
136
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
137

    
138
-- | Safe 'read' function returning data encapsulated in a Result.
139
tryRead :: (Monad m, Read a) => String -> String -> m a
140
tryRead name s = parseChoices name s $ reads s
141

    
142
-- | Format a table of strings to maintain consistent length.
143
formatTable :: [[String]] -> [Bool] -> [[String]]
144
formatTable vals numpos =
145
    let vtrans = transpose vals  -- transpose, so that we work on rows
146
                                 -- rather than columns
147
        mlens = map (maximum . map length) vtrans
148
        expnd = map (\(flds, isnum, ml) ->
149
                         map (\val ->
150
                                  let delta = ml - length val
151
                                      filler = replicate delta ' '
152
                                  in if delta > 0
153
                                     then if isnum
154
                                          then filler ++ val
155
                                          else val ++ filler
156
                                     else val
157
                             ) flds
158
                    ) (zip3 vtrans numpos mlens)
159
   in transpose expnd
160

    
161
-- | Constructs a printable table from given header and rows
162
printTable :: String -> [String] -> [[String]] -> [Bool] -> String
163
printTable lp header rows isnum =
164
  unlines . map ((++) lp) . map ((:) ' ' . unwords) $
165
  formatTable (header:rows) isnum
166

    
167
-- | Converts a unit (e.g. m or GB) into a scaling factor.
168
parseUnitValue :: (Monad m) => String -> m Rational
169
parseUnitValue unit
170
  -- binary conversions first
171
  | null unit                     = return 1
172
  | unit == "m" || upper == "MIB" = return 1
173
  | unit == "g" || upper == "GIB" = return kbBinary
174
  | unit == "t" || upper == "TIB" = return $ kbBinary * kbBinary
175
  -- SI conversions
176
  | unit == "M" || upper == "MB"  = return mbFactor
177
  | unit == "G" || upper == "GB"  = return $ mbFactor * kbDecimal
178
  | unit == "T" || upper == "TB"  = return $ mbFactor * kbDecimal * kbDecimal
179
  | otherwise = fail $ "Unknown unit '" ++ unit ++ "'"
180
  where upper = map toUpper unit
181
        kbBinary = 1024
182
        kbDecimal = 1000
183
        decToBin = kbDecimal / kbBinary -- factor for 1K conversion
184
        mbFactor = decToBin * decToBin -- twice the factor for just 1K
185

    
186
-- | Tries to extract number and scale from the given string.
187
--
188
-- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is
189
-- specified, it defaults to MiB. Return value is always an integral
190
-- value in MiB.
191
parseUnit :: (Monad m, Integral a, Read a) => String -> m a
192
parseUnit str =
193
  -- TODO: enhance this by splitting the unit parsing code out and
194
  -- accepting floating-point numbers
195
  case (reads str::[(Int, String)]) of
196
    [(v, suffix)] ->
197
      let unit = dropWhile (== ' ') suffix
198
      in do
199
        scaling <- parseUnitValue unit
200
        return $ truncate (fromIntegral v * scaling)
201
    _ -> fail $ "Can't parse string '" ++ str ++ "'"