1 {-| Utility functions -}
5 Copyright (C) 2009, 2010 Google Inc.
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.
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.
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
24 module Ganeti.HTools.Utils
47 import Control.Monad (liftM)
49 import qualified Text.JSON as J
50 import Text.Printf (printf)
54 import Ganeti.HTools.Types
58 -- | To be used only for debugging, breaks referential integrity.
59 debug :: Show a => a -> a
60 debug x = trace (show x) x
62 -- | Displays a modified form of the second parameter before returning it
63 debugFn :: Show b => (a -> b) -> a -> a
64 debugFn fn x = debug (fn x) `seq` x
66 -- | Show the first parameter before returning the second one
67 debugXy :: Show a => a -> b -> b
68 debugXy a b = debug a `seq` b
72 -- | Comma-join a string list.
73 commaJoin :: [String] -> String
74 commaJoin = intercalate ","
76 -- | Split a list on a separator and return an array.
77 sepSplit :: Eq a => a -> [a] -> [[a]]
82 | otherwise = x:sepSplit sep ys
83 where (x, xs) = break (== sep) s
86 -- * Mathematical functions
88 -- Simple and slow statistical functions, please replace with better
91 -- | Our modified standard deviation function (not, it's not the variance)
92 varianceCoeff :: [Double] -> Double
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 ->
99 in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
100 ll = fromIntegral ll'::Double
102 av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
103 bv = sqrt (av / ll) -- stddev
104 cv = bv / ll -- standard deviation divided by list length
107 -- * JSON-related functions
109 -- | Converts a JSON Result into a monadic value.
110 fromJResult :: Monad m => String -> J.Result a -> m a
111 fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
112 fromJResult _ (J.Ok x) = return x
114 -- | Tries to read a string from a JSON value.
116 -- In case the value was not a string, we fail the read (in the
117 -- context of the current monad.
118 readEitherString :: (Monad m) => J.JSValue -> m String
121 J.JSString s -> return $ J.fromJSString s
122 _ -> fail "Wrong JSON type"
124 -- | Converts a JSON message into an array of JSON objects.
125 loadJSArray :: (Monad m)
126 => String -- ^ Operation description (for error reporting)
127 -> String -- ^ Input message
128 -> m [J.JSObject J.JSValue]
129 loadJSArray s = fromJResult s . J.decodeStrict
131 -- | Reads the value of a key in a JSON object.
132 fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
135 Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
136 Just val -> fromKeyValue k val
138 -- | Reads the value of an optional key in a JSON object.
139 maybeFromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)]
143 Nothing -> return Nothing
144 Just val -> liftM Just (fromKeyValue k val)
146 -- | Reads a JValue, that originated from an object key
147 fromKeyValue :: (J.JSON a, Monad m)
148 => String -- ^ The key name
149 -> J.JSValue -- ^ The value to read
152 fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
154 -- | Annotate a Result with an ownership information
155 annotateResult :: String -> Result a -> Result a
156 annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
157 annotateResult _ v = v
159 -- | Try to extract a key from a object with better error reporting
161 tryFromObj :: (J.JSON a) =>
162 String -> [(String, J.JSValue)] -> String -> Result a
163 tryFromObj t o k = annotateResult t (fromObj k o)
165 -- | Small wrapper over readJSON.
166 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
169 J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
172 -- | Converts a JSON value into a JSON object.
173 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
174 asJSObject (J.JSObject a) = return a
175 asJSObject _ = fail "not an object"
177 -- | Coneverts a list of JSON values into a list of JSON objects.
178 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
179 asObjectList = mapM asJSObject
181 -- * Parsing utility functions
183 -- | Parse results from readsPrec
184 parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
185 parseChoices _ _ ((v, ""):[]) = return v
186 parseChoices name s ((_, e):[]) =
187 fail $ name ++ ": leftover characters when parsing '"
188 ++ s ++ "': '" ++ e ++ "'"
189 parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
191 -- | Safe 'read' function returning data encapsulated in a Result.
192 tryRead :: (Monad m, Read a) => String -> String -> m a
193 tryRead name s = parseChoices name s $ reads s
195 -- | Format a table of strings to maintain consistent length
196 formatTable :: [[String]] -> [Bool] -> [[String]]
197 formatTable vals numpos =
198 let vtrans = transpose vals -- transpose, so that we work on rows
199 -- rather than columns
200 mlens = map (maximum . map length) vtrans
201 expnd = map (\(flds, isnum, ml) ->
203 let delta = ml - length val
204 filler = replicate delta ' '
211 ) (zip3 vtrans numpos mlens)
214 -- | Default group UUID (just a string, not a real UUID)
215 defaultGroupID :: GroupID
216 defaultGroupID = "00000000-0000-0000-0000-000000000000"