## root / htools / Ganeti / HTools / Utils.hs @ c3024b7e

History | View | Annotate | Download (6.4 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 | |

44 |
import Debug.Trace |

45 | |

46 |
-- * Debug functions |

47 | |

48 |
-- | To be used only for debugging, breaks referential integrity. |

49 |
debug :: Show a => a -> a |

50 |
debug x = trace (show x) x |

51 | |

52 |
-- | Displays a modified form of the second parameter before returning |

53 |
-- it. |

54 |
debugFn :: Show b => (a -> b) -> a -> a |

55 |
debugFn fn x = debug (fn x) `seq` x |

56 | |

57 |
-- | Show the first parameter before returning the second one. |

58 |
debugXy :: Show a => a -> b -> b |

59 |
debugXy = seq . debug |

60 | |

61 |
-- * Miscellaneous |

62 | |

63 |
-- | Apply the function if condition holds, otherwise use default value. |

64 |
applyIf :: Bool -> (a -> a) -> a -> a |

65 |
applyIf b f x = if b then f x else x |

66 | |

67 |
-- | Comma-join a string list. |

68 |
commaJoin :: [String] -> String |

69 |
commaJoin = intercalate "," |

70 | |

71 |
-- | Split a list on a separator and return an array. |

72 |
sepSplit :: Eq a => a -> [a] -> [[a]] |

73 |
sepSplit sep s |

74 |
| null s = [] |

75 |
| null xs = [x] |

76 |
| null ys = [x,[]] |

77 |
| otherwise = x:sepSplit sep ys |

78 |
where (x, xs) = break (== sep) s |

79 |
ys = drop 1 xs |

80 | |

81 |
-- | Simple pluralize helper |

82 |
plural :: Int -> String -> String -> String |

83 |
plural 1 s _ = s |

84 |
plural _ _ p = p |

85 | |

86 |
-- * Mathematical functions |

87 | |

88 |
-- Simple and slow statistical functions, please replace with better |

89 |
-- versions |

90 | |

91 |
-- | Standard deviation function. |

92 |
stdDev :: [Double] -> Double |

93 |
stdDev lst = |

94 |
-- first, calculate the list length and sum lst in a single step, |

95 |
-- for performance reasons |

96 |
let (ll', sx) = foldl' (\(rl, rs) e -> |

97 |
let rl' = rl + 1 |

98 |
rs' = rs + e |

99 |
in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst |

100 |
ll = fromIntegral ll'::Double |

101 |
mv = sx / ll |

102 |
av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst |

103 |
in sqrt (av / ll) -- stddev |

104 | |

105 |
-- * Logical functions |

106 | |

107 |
-- Avoid syntactic sugar and enhance readability. These functions are proposed |

108 |
-- by some for inclusion in the Prelude, and at the moment they are present |

109 |
-- (with various definitions) in the utility-ht package. Some rationale and |

110 |
-- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else> |

111 | |

112 |
-- | \"if\" as a function, rather than as syntactic sugar. |

113 |
if' :: Bool -- ^ condition |

114 |
-> a -- ^ \"then\" result |

115 |
-> a -- ^ \"else\" result |

116 |
-> a -- ^ \"then\" or "else" result depending on the condition |

117 |
if' True x _ = x |

118 |
if' _ _ y = y |

119 | |

120 |
-- | Return the first result with a True condition, or the default otherwise. |

121 |
select :: a -- ^ default result |

122 |
-> [(Bool, a)] -- ^ list of \"condition, result\" |

123 |
-> a -- ^ first result which has a True condition, or default |

124 |
select def = maybe def snd . find fst |

125 | |

126 | |

127 |
-- * Parsing utility functions |

128 | |

129 |
-- | Parse results from readsPrec. |

130 |
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a |

131 |
parseChoices _ _ ((v, ""):[]) = return v |

132 |
parseChoices name s ((_, e):[]) = |

133 |
fail $ name ++ ": leftover characters when parsing '" |

134 |
++ s ++ "': '" ++ e ++ "'" |

135 |
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'" |

136 | |

137 |
-- | Safe 'read' function returning data encapsulated in a Result. |

138 |
tryRead :: (Monad m, Read a) => String -> String -> m a |

139 |
tryRead name s = parseChoices name s $ reads s |

140 | |

141 |
-- | Format a table of strings to maintain consistent length. |

142 |
formatTable :: [[String]] -> [Bool] -> [[String]] |

143 |
formatTable vals numpos = |

144 |
let vtrans = transpose vals -- transpose, so that we work on rows |

145 |
-- rather than columns |

146 |
mlens = map (maximum . map length) vtrans |

147 |
expnd = map (\(flds, isnum, ml) -> |

148 |
map (\val -> |

149 |
let delta = ml - length val |

150 |
filler = replicate delta ' ' |

151 |
in if delta > 0 |

152 |
then if isnum |

153 |
then filler ++ val |

154 |
else val ++ filler |

155 |
else val |

156 |
) flds |

157 |
) (zip3 vtrans numpos mlens) |

158 |
in transpose expnd |

159 | |

160 |
-- | Constructs a printable table from given header and rows |

161 |
printTable :: String -> [String] -> [[String]] -> [Bool] -> String |

162 |
printTable lp header rows isnum = |

163 |
unlines . map ((++) lp) . map ((:) ' ' . unwords) $ |

164 |
formatTable (header:rows) isnum |

165 | |

166 |
-- | Tries to extract number and scale from the given string. |

167 |
-- |

168 |
-- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is |

169 |
-- specified, it defaults to MiB. Return value is always an integral |

170 |
-- value in MiB. |

171 |
parseUnit :: (Monad m, Integral a, Read a) => String -> m a |

172 |
parseUnit str = |

173 |
-- TODO: enhance this by splitting the unit parsing code out and |

174 |
-- accepting floating-point numbers |

175 |
case reads str of |

176 |
[(v, suffix)] -> |

177 |
let unit = dropWhile (== ' ') suffix |

178 |
upper = map toUpper unit |

179 |
siConvert x = x * 1000000 `div` 1048576 |

180 |
in case () of |

181 |
_ | null unit -> return v |

182 |
| unit == "m" || upper == "MIB" -> return v |

183 |
| unit == "M" || upper == "MB" -> return $ siConvert v |

184 |
| unit == "g" || upper == "GIB" -> return $ v * 1024 |

185 |
| unit == "G" || upper == "GB" -> return $ siConvert |

186 |
(v * 1000) |

187 |
| unit == "t" || upper == "TIB" -> return $ v * 1048576 |

188 |
| unit == "T" || upper == "TB" -> return $ |

189 |
siConvert (v * 1000000) |

190 |
| otherwise -> fail $ "Unknown unit '" ++ unit ++ "'" |

191 |
_ -> fail $ "Can't parse string '" ++ str ++ "'" |