Add new CLI options for min gain during balancing
[ganeti-local] / Ganeti / HTools / Utils.hs
1 {-| Utility functions -}
2
3 {-
4
5 Copyright (C) 2009, 2010 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     , debugFn
28     , debugXy
29     , sepSplit
30     , varianceCoeff
31     , commaJoin
32     , readEitherString
33     , loadJSArray
34     , fromObj
35     , maybeFromObj
36     , tryFromObj
37     , fromJVal
38     , asJSObject
39     , asObjectList
40     , fromJResult
41     , tryRead
42     , formatTable
43     , annotateResult
44     ) where
45
46 import Control.Monad (liftM)
47 import Data.List
48 import qualified Text.JSON as J
49 import Text.Printf (printf)
50
51 import Debug.Trace
52
53 import Ganeti.HTools.Types
54
55 -- * Debug functions
56
57 -- | To be used only for debugging, breaks referential integrity.
58 debug :: Show a => a -> a
59 debug x = trace (show x) x
60
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
64
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
68
69 -- * Miscelaneous
70
71 -- | Comma-join a string list.
72 commaJoin :: [String] -> String
73 commaJoin = intercalate ","
74
75 -- | Split a string on a separator and return an array.
76 sepSplit :: Char -> String -> [String]
77 sepSplit sep s
78     | x == "" && xs == [] = []
79     | xs == []            = [x]
80     | ys == []            = [x,""]
81     | otherwise           = x:sepSplit sep ys
82     where (x, xs) = break (== sep) s
83           ys = drop 1 xs
84
85 -- * Mathematical functions
86
87 -- Simple and slow statistical functions, please replace with better
88 -- versions
89
90 -- | The covariance of the list
91 varianceCoeff :: [Double] -> Double
92 varianceCoeff lst =
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
98     in cv
99
100 -- * JSON-related functions
101
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
106
107 -- | Tries to read a string from a JSON value.
108 --
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
112 readEitherString v =
113     case v of
114       J.JSString s -> return $ J.fromJSString s
115       _ -> fail "Wrong JSON type"
116
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
123
124 -- | Reads the value of a key in a JSON object.
125 fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
126 fromObj k o =
127     case lookup k o of
128       Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
129       Just val -> fromKeyValue k val
130
131 -- | Reads the value of an optional key in a JSON object.
132 maybeFromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)]
133                 -> m (Maybe a)
134 maybeFromObj k o =
135     case lookup k o of
136       Nothing -> return Nothing
137       Just val -> liftM Just (fromKeyValue k val)
138
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
143               -> m a
144 fromKeyValue k val =
145   fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
146
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
151
152 -- | Try to extract a key from a object with better error reporting
153 -- than fromObj
154 tryFromObj :: (J.JSON a) =>
155               String -> [(String, J.JSValue)] -> String -> Result a
156 tryFromObj t o k = annotateResult t (fromObj k o)
157
158 -- | Small wrapper over readJSON.
159 fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
160 fromJVal v =
161     case J.readJSON v of
162       J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
163       J.Ok x -> return x
164
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"
169
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
173
174 -- * Parsing utility functions
175
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 ++ "'"
183
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
187
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) ->
195                          map (\val ->
196                                   let delta = ml - length val
197                                       filler = replicate delta ' '
198                                   in if delta > 0
199                                      then if isnum
200                                           then filler ++ val
201                                           else val ++ filler
202                                      else val
203                              ) flds
204                     ) (zip3 vtrans numpos mlens)
205    in transpose expnd