Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Utils.hs @ bfe6c954

History | View | Annotate | Download (8.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
    (
26
      debug
27
    , debugFn
28
    , debugXy
29
    , sepSplit
30
    , stdDev
31
    , if'
32
    , select
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
    , annotateResult
48
    , defaultGroupID
49
    ) where
50

    
51
import Control.Monad (liftM)
52
import Data.List
53
import Data.Maybe (fromMaybe)
54
import qualified Text.JSON as J
55
import Text.Printf (printf)
56

    
57
import Debug.Trace
58

    
59
import Ganeti.HTools.Types
60

    
61
-- * Debug functions
62

    
63
-- | To be used only for debugging, breaks referential integrity.
64
debug :: Show a => a -> a
65
debug x = trace (show x) x
66

    
67
-- | Displays a modified form of the second parameter before returning
68
-- it.
69
debugFn :: Show b => (a -> b) -> a -> a
70
debugFn fn x = debug (fn x) `seq` x
71

    
72
-- | Show the first parameter before returning the second one.
73
debugXy :: Show a => a -> b -> b
74
debugXy a b = debug a `seq` b
75

    
76
-- * Miscellaneous
77

    
78
-- | Comma-join a string list.
79
commaJoin :: [String] -> String
80
commaJoin = intercalate ","
81

    
82
-- | Split a list on a separator and return an array.
83
sepSplit :: Eq a => a -> [a] -> [[a]]
84
sepSplit sep s
85
    | null s    = []
86
    | null xs   = [x]
87
    | null ys   = [x,[]]
88
    | otherwise = x:sepSplit sep ys
89
    where (x, xs) = break (== sep) s
90
          ys = drop 1 xs
91

    
92
-- * Mathematical functions
93

    
94
-- Simple and slow statistical functions, please replace with better
95
-- versions
96

    
97
-- | Standard deviation function.
98
stdDev :: [Double] -> Double
99
stdDev lst =
100
  -- first, calculate the list length and sum lst in a single step,
101
  -- for performance reasons
102
  let (ll', sx) = foldl' (\(rl, rs) e ->
103
                           let rl' = rl + 1
104
                               rs' = rs + e
105
                           in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
106
      ll = fromIntegral ll'::Double
107
      mv = sx / ll
108
      av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
109
  in sqrt (av / ll) -- stddev
110

    
111
-- *  Logical functions
112

    
113
-- Avoid syntactic sugar and enhance readability. These functions are proposed
114
-- by some for inclusion in the Prelude, and at the moment they are present
115
-- (with various definitions) in the utility-ht package. Some rationale and
116
-- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else>
117

    
118
-- | \"if\" as a function, rather than as syntactic sugar.
119
if' :: Bool -- ^ condition
120
    -> a    -- ^ \"then\" result
121
    -> a    -- ^ \"else\" result
122
    -> a    -- ^ \"then\" or "else" result depending on the condition
123
if' True x _ = x
124
if' _    _ y = y
125

    
126
-- | Return the first result with a True condition, or the default otherwise.
127
select :: a            -- ^ default result
128
       -> [(Bool, a)]  -- ^ list of \"condition, result\"
129
       -> a            -- ^ first result which has a True condition, or default
130
select def = maybe def snd . find fst
131

    
132
-- * JSON-related functions
133

    
134
-- | A type alias for the list-based representation of J.JSObject.
135
type JSRecord = [(String, J.JSValue)]
136

    
137
-- | Converts a JSON Result into a monadic value.
138
fromJResult :: Monad m => String -> J.Result a -> m a
139
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
140
fromJResult _ (J.Ok x) = return x
141

    
142
-- | Tries to read a string from a JSON value.
143
--
144
-- In case the value was not a string, we fail the read (in the
145
-- context of the current monad.
146
readEitherString :: (Monad m) => J.JSValue -> m String
147
readEitherString v =
148
    case v of
149
      J.JSString s -> return $ J.fromJSString s
150
      _ -> fail "Wrong JSON type"
151

    
152
-- | Converts a JSON message into an array of JSON objects.
153
loadJSArray :: (Monad m)
154
               => String -- ^ Operation description (for error reporting)
155
               -> String -- ^ Input message
156
               -> m [J.JSObject J.JSValue]
157
loadJSArray s = fromJResult s . J.decodeStrict
158

    
159
-- | Reads the value of a key in a JSON object.
160
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
161
fromObj o k =
162
    case lookup k o of
163
      Nothing -> fail $ printf "key '%s' not found, object contains only %s"
164
                 k (show (map fst o))
165
      Just val -> fromKeyValue k val
166

    
167
-- | Reads the value of an optional key in a JSON object.
168
maybeFromObj :: (J.JSON a, Monad m) =>
169
                JSRecord -> String -> m (Maybe a)
170
maybeFromObj o k =
171
    case lookup k o of
172
      Nothing -> return Nothing
173
      Just val -> liftM Just (fromKeyValue k val)
174

    
175
-- | Reads the value of a key in a JSON object with a default if missing.
176
fromObjWithDefault :: (J.JSON a, Monad m) =>
177
                      JSRecord -> String -> a -> m a
178
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
179

    
180
-- | Reads a JValue, that originated from an object key.
181
fromKeyValue :: (J.JSON a, Monad m)
182
              => String     -- ^ The key name
183
              -> J.JSValue  -- ^ The value to read
184
              -> m a
185
fromKeyValue k val =
186
  fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
187

    
188
-- | Annotate a Result with an ownership information.
189
annotateResult :: String -> Result a -> Result a
190
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
191
annotateResult _ v = v
192

    
193
-- | Try to extract a key from a object with better error reporting
194
-- than fromObj.
195
tryFromObj :: (J.JSON a) =>
196
              String     -- ^ Textual "owner" in error messages
197
           -> JSRecord   -- ^ The object array
198
           -> String     -- ^ The desired key from the object
199
           -> Result a
200
tryFromObj t o = annotateResult t . fromObj o
201

    
202
-- | Small wrapper over readJSON.
203
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
204
fromJVal v =
205
    case J.readJSON v of
206
      J.Error s -> fail ("Cannot convert value '" ++ show v ++
207
                         "', error: " ++ s)
208
      J.Ok x -> return x
209

    
210
-- | Converts a JSON value into a JSON object.
211
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
212
asJSObject (J.JSObject a) = return a
213
asJSObject _ = fail "not an object"
214

    
215
-- | Coneverts a list of JSON values into a list of JSON objects.
216
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
217
asObjectList = mapM asJSObject
218

    
219
-- * Parsing utility functions
220

    
221
-- | Parse results from readsPrec.
222
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
223
parseChoices _ _ ((v, ""):[]) = return v
224
parseChoices name s ((_, e):[]) =
225
    fail $ name ++ ": leftover characters when parsing '"
226
           ++ s ++ "': '" ++ e ++ "'"
227
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
228

    
229
-- | Safe 'read' function returning data encapsulated in a Result.
230
tryRead :: (Monad m, Read a) => String -> String -> m a
231
tryRead name s = parseChoices name s $ reads s
232

    
233
-- | Format a table of strings to maintain consistent length.
234
formatTable :: [[String]] -> [Bool] -> [[String]]
235
formatTable vals numpos =
236
    let vtrans = transpose vals  -- transpose, so that we work on rows
237
                                 -- rather than columns
238
        mlens = map (maximum . map length) vtrans
239
        expnd = map (\(flds, isnum, ml) ->
240
                         map (\val ->
241
                                  let delta = ml - length val
242
                                      filler = replicate delta ' '
243
                                  in if delta > 0
244
                                     then if isnum
245
                                          then filler ++ val
246
                                          else val ++ filler
247
                                     else val
248
                             ) flds
249
                    ) (zip3 vtrans numpos mlens)
250
   in transpose expnd
251

    
252
-- | Default group UUID (just a string, not a real UUID).
253
defaultGroupID :: GroupID
254
defaultGroupID = "00000000-0000-0000-0000-000000000000"