root / htools / Ganeti / HTools / Utils.hs @ f3f76ccc
History | View | Annotate | Download (6.3 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 |
, readEitherString |
35 |
, JSRecord |
36 |
, loadJSArray |
37 |
, fromObj |
38 |
, fromObjWithDefault |
39 |
, maybeFromObj |
40 |
, tryFromObj |
41 |
, fromJVal |
42 |
, asJSObject |
43 |
, asObjectList |
44 |
, fromJResult |
45 |
, tryRead |
46 |
, formatTable |
47 |
, parseUnit |
48 |
) where |
49 |
|
50 |
import Data.Char (toUpper) |
51 |
import Data.List |
52 |
|
53 |
import Debug.Trace |
54 |
|
55 |
-- we will re-export these for our existing users |
56 |
import Ganeti.HTools.JSON |
57 |
|
58 |
-- * Debug functions |
59 |
|
60 |
-- | To be used only for debugging, breaks referential integrity. |
61 |
debug :: Show a => a -> a |
62 |
debug x = trace (show x) x |
63 |
|
64 |
-- | Displays a modified form of the second parameter before returning |
65 |
-- it. |
66 |
debugFn :: Show b => (a -> b) -> a -> a |
67 |
debugFn fn x = debug (fn x) `seq` x |
68 |
|
69 |
-- | Show the first parameter before returning the second one. |
70 |
debugXy :: Show a => a -> b -> b |
71 |
debugXy = seq . debug |
72 |
|
73 |
-- * Miscellaneous |
74 |
|
75 |
-- | Apply the function if condition holds, otherwise use default value. |
76 |
applyIf :: Bool -> (a -> a) -> a -> a |
77 |
applyIf b f x = if b then f x else x |
78 |
|
79 |
-- | Comma-join a string list. |
80 |
commaJoin :: [String] -> String |
81 |
commaJoin = intercalate "," |
82 |
|
83 |
-- | Split a list on a separator and return an array. |
84 |
sepSplit :: Eq a => a -> [a] -> [[a]] |
85 |
sepSplit sep s |
86 |
| null s = [] |
87 |
| null xs = [x] |
88 |
| null ys = [x,[]] |
89 |
| otherwise = x:sepSplit sep ys |
90 |
where (x, xs) = break (== sep) s |
91 |
ys = drop 1 xs |
92 |
|
93 |
-- * Mathematical functions |
94 |
|
95 |
-- Simple and slow statistical functions, please replace with better |
96 |
-- versions |
97 |
|
98 |
-- | Standard deviation function. |
99 |
stdDev :: [Double] -> Double |
100 |
stdDev lst = |
101 |
-- first, calculate the list length and sum lst in a single step, |
102 |
-- for performance reasons |
103 |
let (ll', sx) = foldl' (\(rl, rs) e -> |
104 |
let rl' = rl + 1 |
105 |
rs' = rs + e |
106 |
in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst |
107 |
ll = fromIntegral ll'::Double |
108 |
mv = sx / ll |
109 |
av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst |
110 |
in sqrt (av / ll) -- stddev |
111 |
|
112 |
-- * Logical functions |
113 |
|
114 |
-- Avoid syntactic sugar and enhance readability. These functions are proposed |
115 |
-- by some for inclusion in the Prelude, and at the moment they are present |
116 |
-- (with various definitions) in the utility-ht package. Some rationale and |
117 |
-- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else> |
118 |
|
119 |
-- | \"if\" as a function, rather than as syntactic sugar. |
120 |
if' :: Bool -- ^ condition |
121 |
-> a -- ^ \"then\" result |
122 |
-> a -- ^ \"else\" result |
123 |
-> a -- ^ \"then\" or "else" result depending on the condition |
124 |
if' True x _ = x |
125 |
if' _ _ y = y |
126 |
|
127 |
-- | Return the first result with a True condition, or the default otherwise. |
128 |
select :: a -- ^ default result |
129 |
-> [(Bool, a)] -- ^ list of \"condition, result\" |
130 |
-> a -- ^ first result which has a True condition, or default |
131 |
select def = maybe def snd . find fst |
132 |
|
133 |
|
134 |
-- * Parsing utility functions |
135 |
|
136 |
-- | Parse results from readsPrec. |
137 |
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a |
138 |
parseChoices _ _ ((v, ""):[]) = return v |
139 |
parseChoices name s ((_, e):[]) = |
140 |
fail $ name ++ ": leftover characters when parsing '" |
141 |
++ s ++ "': '" ++ e ++ "'" |
142 |
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'" |
143 |
|
144 |
-- | Safe 'read' function returning data encapsulated in a Result. |
145 |
tryRead :: (Monad m, Read a) => String -> String -> m a |
146 |
tryRead name s = parseChoices name s $ reads s |
147 |
|
148 |
-- | Format a table of strings to maintain consistent length. |
149 |
formatTable :: [[String]] -> [Bool] -> [[String]] |
150 |
formatTable vals numpos = |
151 |
let vtrans = transpose vals -- transpose, so that we work on rows |
152 |
-- rather than columns |
153 |
mlens = map (maximum . map length) vtrans |
154 |
expnd = map (\(flds, isnum, ml) -> |
155 |
map (\val -> |
156 |
let delta = ml - length val |
157 |
filler = replicate delta ' ' |
158 |
in if delta > 0 |
159 |
then if isnum |
160 |
then filler ++ val |
161 |
else val ++ filler |
162 |
else val |
163 |
) flds |
164 |
) (zip3 vtrans numpos mlens) |
165 |
in transpose expnd |
166 |
|
167 |
-- | Tries to extract number and scale from the given string. |
168 |
-- |
169 |
-- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is |
170 |
-- specified, it defaults to MiB. Return value is always an integral |
171 |
-- value in MiB. |
172 |
parseUnit :: (Monad m, Integral a, Read a) => String -> m a |
173 |
parseUnit str = |
174 |
-- TODO: enhance this by splitting the unit parsing code out and |
175 |
-- accepting floating-point numbers |
176 |
case reads str of |
177 |
[(v, suffix)] -> |
178 |
let unit = dropWhile (== ' ') suffix |
179 |
upper = map toUpper unit |
180 |
siConvert x = x * 1000000 `div` 1048576 |
181 |
in case () of |
182 |
_ | null unit -> return v |
183 |
| unit == "m" || upper == "MIB" -> return v |
184 |
| unit == "M" || upper == "MB" -> return $ siConvert v |
185 |
| unit == "g" || upper == "GIB" -> return $ v * 1024 |
186 |
| unit == "G" || upper == "GB" -> return $ siConvert |
187 |
(v * 1000) |
188 |
| unit == "t" || upper == "TIB" -> return $ v * 1048576 |
189 |
| unit == "T" || upper == "TB" -> return $ |
190 |
siConvert (v * 1000000) |
191 |
| otherwise -> fail $ "Unknown unit '" ++ unit ++ "'" |
192 |
_ -> fail $ "Can't parse string '" ++ str ++ "'" |