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
46 import Control.Monad (liftM)
48 import qualified Text.JSON as J
49 import Text.Printf (printf)
53 import Ganeti.HTools.Types
57 -- | To be used only for debugging, breaks referential integrity.
58 debug :: Show a => a -> a
59 debug x = trace (show x) x
61 -- | Displays a modified form of the second parameter before returning it
62 debugFn :: Show b => (a -> b) -> a -> a
63 debugFn fn x = debug (fn x) `seq` x
65 -- | Show the first parameter before returning the second one
66 debugXy :: Show a => a -> b -> b
67 debugXy a b = debug a `seq` b
71 -- | Comma-join a string list.
72 commaJoin :: [String] -> String
73 commaJoin = intercalate ","
75 -- | Split a string on a separator and return an array.
76 sepSplit :: Char -> String -> [String]
78 | x == "" && xs == [] = []
81 | otherwise = x:sepSplit sep ys
82 where (x, xs) = break (== sep) s
85 -- * Mathematical functions
87 -- Simple and slow statistical functions, please replace with better
90 -- | The covariance of the list
91 varianceCoeff :: [Double] -> Double
93 let ll = fromIntegral (length lst)::Double -- length of list
94 mv = sum lst / ll -- mean value
95 av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
96 bv = sqrt (av / ll) -- stddev
97 cv = bv / ll -- covariance
100 -- * JSON-related functions
102 -- | Converts a JSON Result into a monadic value.
103 fromJResult :: Monad m => String -> J.Result a -> m a
104 fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
105 fromJResult _ (J.Ok x) = return x
107 -- | Tries to read a string from a JSON value.
109 -- In case the value was not a string, we fail the read (in the
110 -- context of the current monad.
111 readEitherString :: (Monad m) => J.JSValue -> m String
114 J.JSString s -> return $ J.fromJSString s
115 _ -> fail "Wrong JSON type"
117 -- | Converts a JSON message into an array of JSON objects.
118 loadJSArray :: (Monad m)
119 => String -- ^ Operation description (for error reporting)
120 -> String -- ^ Input message
121 -> m [J.JSObject J.JSValue]
122 loadJSArray s = fromJResult s . J.decodeStrict
124 -- | Reads the value of a key in a JSON object.
125 fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
128 Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
129 Just val -> fromKeyValue k val
131 -- | Reads the value of an optional key in a JSON object.
132 maybeFromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)]
136 Nothing -> return Nothing
137 Just val -> liftM Just (fromKeyValue k val)
139 -- | Reads a JValue, that originated from an object key
140 fromKeyValue :: (J.JSON a, Monad m)
141 => String -- ^ The key name
142 -> J.JSValue -- ^ The value to read
145 fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
147 -- | Annotate a Result with an ownership information
148 annotateResult :: String -> Result a -> Result a
149 annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
150 annotateResult _ v = v
152 -- | Try to extract a key from a object with better error reporting
154 tryFromObj :: (J.JSON a) =>
155 String -> [(String, J.JSValue)] -> String -> Result a
156 tryFromObj t o k = annotateResult t (fromObj k o)
158 -- | Small wrapper over readJSON.
159 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
162 J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
165 -- | Converts a JSON value into a JSON object.
166 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
167 asJSObject (J.JSObject a) = return a
168 asJSObject _ = fail "not an object"
170 -- | Coneverts a list of JSON values into a list of JSON objects.
171 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
172 asObjectList = mapM asJSObject
174 -- * Parsing utility functions
176 -- | Parse results from readsPrec
177 parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
178 parseChoices _ _ ((v, ""):[]) = return v
179 parseChoices name s ((_, e):[]) =
180 fail $ name ++ ": leftover characters when parsing '"
181 ++ s ++ "': '" ++ e ++ "'"
182 parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
184 -- | Safe 'read' function returning data encapsulated in a Result.
185 tryRead :: (Monad m, Read a) => String -> String -> m a
186 tryRead name s = parseChoices name s $ reads s
188 -- | Format a table of strings to maintain consistent length
189 formatTable :: [[String]] -> [Bool] -> [[String]]
190 formatTable vals numpos =
191 let vtrans = transpose vals -- transpose, so that we work on rows
192 -- rather than columns
193 mlens = map (maximum . map length) vtrans
194 expnd = map (\(flds, isnum, ml) ->
196 let delta = ml - length val
197 filler = replicate delta ' '
204 ) (zip3 vtrans numpos mlens)