0d585b693cc61348321d84eb63f3cfffae524075
[ganeti-local] / Ganeti / HTools / Utils.hs
1 {-| Utility functions -}
2
3 {-
4
5 Copyright (C) 2009 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     (
26       debug
27     , sepSplit
28     , varianceCoeff
29     , commaJoin
30     , readEitherString
31     , loadJSArray
32     , fromObj
33     , maybeFromObj
34     , tryFromObj
35     , fromJVal
36     , asJSObject
37     , asObjectList
38     , fromJResult
39     , tryRead
40     , formatTable
41     , annotateResult
42     ) where
43
44 import Control.Monad (liftM)
45 import Data.List
46 import qualified Text.JSON as J
47 import Text.Printf (printf)
48
49 import Debug.Trace
50
51 import Ganeti.HTools.Types
52
53 -- * Debug functions
54
55 -- | To be used only for debugging, breaks referential integrity.
56 debug :: Show a => a -> a
57 debug x = trace (show x) x
58
59 -- * Miscelaneous
60
61 -- | Comma-join a string list.
62 commaJoin :: [String] -> String
63 commaJoin = intercalate ","
64
65 -- | Split a string on a separator and return an array.
66 sepSplit :: Char -> String -> [String]
67 sepSplit sep s
68     | x == "" && xs == [] = []
69     | xs == []            = [x]
70     | ys == []            = [x,""]
71     | otherwise           = x:sepSplit sep ys
72     where (x, xs) = break (== sep) s
73           ys = drop 1 xs
74
75 -- * Mathematical functions
76
77 -- Simple and slow statistical functions, please replace with better
78 -- versions
79
80 -- | The covariance of the list
81 varianceCoeff :: [Double] -> Double
82 varianceCoeff lst =
83     let ll = fromIntegral (length lst)::Double -- length of list
84         mv = sum lst / ll   -- mean value
85         av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
86         bv = sqrt (av / ll) -- stddev
87         cv = bv / ll        -- covariance
88     in cv
89
90 -- * JSON-related functions
91
92 -- | Converts a JSON Result into a monadic value.
93 fromJResult :: Monad m => String -> J.Result a -> m a
94 fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
95 fromJResult _ (J.Ok x) = return x
96
97 -- | Tries to read a string from a JSON value.
98 --
99 -- In case the value was not a string, we fail the read (in the
100 -- context of the current monad.
101 readEitherString :: (Monad m) => J.JSValue -> m String
102 readEitherString v =
103     case v of
104       J.JSString s -> return $ J.fromJSString s
105       _ -> fail "Wrong JSON type"
106
107 -- | Converts a JSON message into an array of JSON objects.
108 loadJSArray :: (Monad m)
109                => String -- ^ Operation description (for error reporting)
110                -> String -- ^ Input message
111                -> m [J.JSObject J.JSValue]
112 loadJSArray s = fromJResult s . J.decodeStrict
113
114 -- | Reads the value of a key in a JSON object.
115 fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
116 fromObj k o =
117     case lookup k o of
118       Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
119       Just val -> fromKeyValue k val
120
121 -- | Reads the value of an optional key in a JSON object.
122 maybeFromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)]
123                 -> m (Maybe a)
124 maybeFromObj k o =
125     case lookup k o of
126       Nothing -> return Nothing
127       Just val -> liftM Just (fromKeyValue k val)
128
129 -- | Reads a JValue, that originated from an object key
130 fromKeyValue :: (J.JSON a, Monad m)
131               => String     -- ^ The key name
132               -> J.JSValue  -- ^ The value to read
133               -> m a
134 fromKeyValue k val =
135   fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
136
137 -- | Annotate a Result with an ownership information
138 annotateResult :: String -> Result a -> Result a
139 annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
140 annotateResult _ v = v
141
142 -- | Try to extract a key from a object with better error reporting
143 -- than fromObj
144 tryFromObj :: (J.JSON a) =>
145               String -> [(String, J.JSValue)] -> String -> Result a
146 tryFromObj t o k = annotateResult t (fromObj k o)
147
148 -- | Small wrapper over readJSON.
149 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
150 fromJVal v =
151     case J.readJSON v of
152       J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
153       J.Ok x -> return x
154
155 -- | Converts a JSON value into a JSON object.
156 asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
157 asJSObject (J.JSObject a) = return a
158 asJSObject _ = fail "not an object"
159
160 -- | Coneverts a list of JSON values into a list of JSON objects.
161 asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
162 asObjectList = mapM asJSObject
163
164 -- * Parsing utility functions
165
166 -- | Parse results from readsPrec
167 parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
168 parseChoices _ _ ((v, ""):[]) = return v
169 parseChoices name s ((_, e):[]) =
170     fail $ name ++ ": leftover characters when parsing '"
171            ++ s ++ "': '" ++ e ++ "'"
172 parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
173
174 -- | Safe 'read' function returning data encapsulated in a Result.
175 tryRead :: (Monad m, Read a) => String -> String -> m a
176 tryRead name s = parseChoices name s $ reads s
177
178 -- | Format a table of strings to maintain consistent length
179 formatTable :: [[String]] -> [Bool] -> [[String]]
180 formatTable vals numpos =
181     let vtrans = transpose vals  -- transpose, so that we work on rows
182                                  -- rather than columns
183         mlens = map (maximum . map length) vtrans
184         expnd = map (\(flds, isnum, ml) ->
185                          map (\val ->
186                                   let delta = ml - length val
187                                       filler = replicate delta ' '
188                                   in if delta > 0
189                                      then if isnum
190                                           then filler ++ val
191                                           else val ++ filler
192                                      else val
193                              ) flds
194                     ) (zip3 vtrans numpos mlens)
195    in transpose expnd