Statistics
| Branch: | Tag: | Revision:

root / Ganeti / HTools / Utils.hs @ e8230242

History | View | Annotate | Download (7 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
    , 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
    , defaultGroupID
45
    ) where
46

    
47
import Control.Monad (liftM)
48
import Data.List
49
import qualified Text.JSON as J
50
import Text.Printf (printf)
51

    
52
import Debug.Trace
53

    
54
import Ganeti.HTools.Types
55

    
56
-- * Debug functions
57

    
58
-- | To be used only for debugging, breaks referential integrity.
59
debug :: Show a => a -> a
60
debug x = trace (show x) x
61

    
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
65

    
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
69

    
70
-- * Miscelaneous
71

    
72
-- | Comma-join a string list.
73
commaJoin :: [String] -> String
74
commaJoin = intercalate ","
75

    
76
-- | Split a list on a separator and return an array.
77
sepSplit :: Eq a => a -> [a] -> [[a]]
78
sepSplit sep s
79
    | null s    = []
80
    | null xs   = [x]
81
    | null ys   = [x,[]]
82
    | otherwise = x:sepSplit sep ys
83
    where (x, xs) = break (== sep) s
84
          ys = drop 1 xs
85

    
86
-- * Mathematical functions
87

    
88
-- Simple and slow statistical functions, please replace with better
89
-- versions
90

    
91
-- | Standard deviation function
92
stdDev :: [Double] -> Double
93
stdDev lst =
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 ->
97
                           let rl' = rl + 1
98
                               rs' = rs + e
99
                           in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
100
      ll = fromIntegral ll'::Double
101
      mv = sx / ll
102
      av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
103
  in sqrt (av / ll) -- stddev
104

    
105
-- * JSON-related functions
106

    
107
-- | Converts a JSON Result into a monadic value.
108
fromJResult :: Monad m => String -> J.Result a -> m a
109
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
110
fromJResult _ (J.Ok x) = return x
111

    
112
-- | Tries to read a string from a JSON value.
113
--
114
-- In case the value was not a string, we fail the read (in the
115
-- context of the current monad.
116
readEitherString :: (Monad m) => J.JSValue -> m String
117
readEitherString v =
118
    case v of
119
      J.JSString s -> return $ J.fromJSString s
120
      _ -> fail "Wrong JSON type"
121

    
122
-- | Converts a JSON message into an array of JSON objects.
123
loadJSArray :: (Monad m)
124
               => String -- ^ Operation description (for error reporting)
125
               -> String -- ^ Input message
126
               -> m [J.JSObject J.JSValue]
127
loadJSArray s = fromJResult s . J.decodeStrict
128

    
129
-- | Reads the value of a key in a JSON object.
130
fromObj :: (J.JSON a, Monad m) => [(String, J.JSValue)] -> String -> m a
131
fromObj o k =
132
    case lookup k o of
133
      Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
134
      Just val -> fromKeyValue k val
135

    
136
-- | Reads the value of an optional key in a JSON object.
137
maybeFromObj :: (J.JSON a, Monad m) =>
138
             [(String, J.JSValue)] -> String -> m (Maybe a)
139
maybeFromObj o k =
140
    case lookup k o of
141
      Nothing -> return Nothing
142
      Just val -> liftM Just (fromKeyValue k val)
143

    
144
-- | Reads a JValue, that originated from an object key
145
fromKeyValue :: (J.JSON a, Monad m)
146
              => String     -- ^ The key name
147
              -> J.JSValue  -- ^ The value to read
148
              -> m a
149
fromKeyValue k val =
150
  fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
151

    
152
-- | Annotate a Result with an ownership information
153
annotateResult :: String -> Result a -> Result a
154
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
155
annotateResult _ v = v
156

    
157
-- | Try to extract a key from a object with better error reporting
158
-- than fromObj
159
tryFromObj :: (J.JSON a) =>
160
              String                -- ^ Textual "owner" in error messages
161
           -> [(String, J.JSValue)] -- ^ The object array
162
           -> String                -- ^ The desired key from the object
163
           -> Result a
164
tryFromObj t o = annotateResult t . fromObj o
165

    
166
-- | Small wrapper over readJSON.
167
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
168
fromJVal v =
169
    case J.readJSON v of
170
      J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
171
      J.Ok x -> return x
172

    
173
-- | Converts a JSON value into a JSON object.
174
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
175
asJSObject (J.JSObject a) = return a
176
asJSObject _ = fail "not an object"
177

    
178
-- | Coneverts a list of JSON values into a list of JSON objects.
179
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
180
asObjectList = mapM asJSObject
181

    
182
-- * Parsing utility functions
183

    
184
-- | Parse results from readsPrec
185
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
186
parseChoices _ _ ((v, ""):[]) = return v
187
parseChoices name s ((_, e):[]) =
188
    fail $ name ++ ": leftover characters when parsing '"
189
           ++ s ++ "': '" ++ e ++ "'"
190
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
191

    
192
-- | Safe 'read' function returning data encapsulated in a Result.
193
tryRead :: (Monad m, Read a) => String -> String -> m a
194
tryRead name s = parseChoices name s $ reads s
195

    
196
-- | Format a table of strings to maintain consistent length
197
formatTable :: [[String]] -> [Bool] -> [[String]]
198
formatTable vals numpos =
199
    let vtrans = transpose vals  -- transpose, so that we work on rows
200
                                 -- rather than columns
201
        mlens = map (maximum . map length) vtrans
202
        expnd = map (\(flds, isnum, ml) ->
203
                         map (\val ->
204
                                  let delta = ml - length val
205
                                      filler = replicate delta ' '
206
                                  in if delta > 0
207
                                     then if isnum
208
                                          then filler ++ val
209
                                          else val ++ filler
210
                                     else val
211
                             ) flds
212
                    ) (zip3 vtrans numpos mlens)
213
   in transpose expnd
214

    
215
-- | Default group UUID (just a string, not a real UUID)
216
defaultGroupID :: GroupID
217
defaultGroupID = "00000000-0000-0000-0000-000000000000"