Statistics
| Branch: | Tag: | Revision:

root / Ganeti / HTools / Utils.hs @ f36a8028

History | View | Annotate | Download (6.4 kB)

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
    , fst3
29
    , varianceCoeff
30
    , commaJoin
31
    , readEitherString
32
    , loadJSArray
33
    , fromObj
34
    , maybeFromObj
35
    , tryFromObj
36
    , fromJVal
37
    , asJSObject
38
    , asObjectList
39
    , fromJResult
40
    , tryRead
41
    , formatTable
42
    , annotateResult
43
    ) where
44

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

    
50
import Debug.Trace
51

    
52
import Ganeti.HTools.Types
53

    
54
-- * Debug functions
55

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

    
60
-- * Miscelaneous
61

    
62
-- | Comma-join a string list.
63
commaJoin :: [String] -> String
64
commaJoin = intercalate ","
65

    
66
-- | Split a string on a separator and return an array.
67
sepSplit :: Char -> String -> [String]
68
sepSplit sep s
69
    | x == "" && xs == [] = []
70
    | xs == []            = [x]
71
    | ys == []            = [x,""]
72
    | otherwise           = x:sepSplit sep ys
73
    where (x, xs) = break (== sep) s
74
          ys = drop 1 xs
75

    
76
-- | Simple version of 'fst' for a triple
77
fst3 :: (a, b, c) -> a
78
fst3 (a, _, _) = a
79

    
80
-- * Mathematical functions
81

    
82
-- Simple and slow statistical functions, please replace with better
83
-- versions
84

    
85
-- | The covariance of the list
86
varianceCoeff :: [Double] -> Double
87
varianceCoeff lst =
88
    let ll = fromIntegral (length lst)::Double -- length of list
89
        mv = sum lst / ll   -- mean value
90
        av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
91
        bv = sqrt (av / ll) -- stddev
92
        cv = bv / ll        -- covariance
93
    in cv
94

    
95
-- * JSON-related functions
96

    
97
-- | Converts a JSON Result into a monadic value.
98
fromJResult :: Monad m => String -> J.Result a -> m a
99
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
100
fromJResult _ (J.Ok x) = return x
101

    
102
-- | Tries to read a string from a JSON value.
103
--
104
-- In case the value was not a string, we fail the read (in the
105
-- context of the current monad.
106
readEitherString :: (Monad m) => J.JSValue -> m String
107
readEitherString v =
108
    case v of
109
      J.JSString s -> return $ J.fromJSString s
110
      _ -> fail "Wrong JSON type"
111

    
112
-- | Converts a JSON message into an array of JSON objects.
113
loadJSArray :: (Monad m)
114
               => String -- ^ Operation description (for error reporting)
115
               -> String -- ^ Input message
116
               -> m [J.JSObject J.JSValue]
117
loadJSArray s = fromJResult s . J.decodeStrict
118

    
119
-- | Reads the value of a key in a JSON object.
120
fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
121
fromObj k o =
122
    case lookup k o of
123
      Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
124
      Just val -> fromKeyValue k val
125

    
126
-- | Reads the value of an optional key in a JSON object.
127
maybeFromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)]
128
                -> m (Maybe a)
129
maybeFromObj k o =
130
    case lookup k o of
131
      Nothing -> return Nothing
132
      Just val -> liftM Just (fromKeyValue k val)
133

    
134
-- | Reads a JValue, that originated from an object key
135
fromKeyValue :: (J.JSON a, Monad m)
136
              => String     -- ^ The key name
137
              -> J.JSValue  -- ^ The value to read
138
              -> m a
139
fromKeyValue k val =
140
  fromJResult (printf "key '%s', value '%s'" k (show val)) (J.readJSON val)
141

    
142
-- | Annotate a Result with an ownership information
143
annotateResult :: String -> Result a -> Result a
144
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
145
annotateResult _ v = v
146

    
147
-- | Try to extract a key from a object with better error reporting
148
-- than fromObj
149
tryFromObj :: (J.JSON a) =>
150
              String -> [(String, J.JSValue)] -> String -> Result a
151
tryFromObj t o k = annotateResult t (fromObj k o)
152

    
153
-- | Small wrapper over readJSON.
154
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
155
fromJVal v =
156
    case J.readJSON v of
157
      J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
158
      J.Ok x -> return x
159

    
160
-- | Converts a JSON value into a JSON object.
161
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
162
asJSObject (J.JSObject a) = return a
163
asJSObject _ = fail "not an object"
164

    
165
-- | Coneverts a list of JSON values into a list of JSON objects.
166
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
167
asObjectList = mapM asJSObject
168

    
169
-- * Parsing utility functions
170

    
171
-- | Parse results from readsPrec
172
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
173
parseChoices _ _ ((v, ""):[]) = return v
174
parseChoices name s ((_, e):[]) =
175
    fail $ name ++ ": leftover characters when parsing '"
176
           ++ s ++ "': '" ++ e ++ "'"
177
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
178

    
179
-- | Safe 'read' function returning data encapsulated in a Result.
180
tryRead :: (Monad m, Read a) => String -> String -> m a
181
tryRead name s = parseChoices name s $ reads s
182

    
183
-- | Format a table of strings to maintain consistent length
184
formatTable :: [[String]] -> [Bool] -> [[String]]
185
formatTable vals numpos =
186
    let vtrans = transpose vals  -- transpose, so that we work on rows
187
                                 -- rather than columns
188
        mlens = map (maximum . map length) vtrans
189
        expnd = map (\(flds, isnum, ml) ->
190
                         map (\val ->
191
                                  let delta = ml - length val
192
                                      filler = replicate delta ' '
193
                                  in if delta > 0
194
                                     then if isnum
195
                                          then filler ++ val
196
                                          else val ++ filler
197
                                     else val
198
                             ) flds
199
                    ) (zip3 vtrans numpos mlens)
200
   in transpose expnd