Statistics
| Branch: | Tag: | Revision:

root / Ganeti / HTools / Utils.hs @ c96d44df

History | View | Annotate | Download (5.8 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
    , tryFromObj
35
    , fromJVal
36
    , asJSObject
37
    , asObjectList
38
    , fromJResult
39
    , tryRead
40
    , formatTable
41
    , annotateResult
42
    ) where
43

    
44
import Data.List
45
import qualified Text.JSON as J
46
import Text.Printf (printf)
47

    
48
import Debug.Trace
49

    
50
import Ganeti.HTools.Types
51

    
52
-- * Debug functions
53

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

    
58
-- * Miscelaneous
59

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

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

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

    
78
-- * Mathematical functions
79

    
80
-- Simple and slow statistical functions, please replace with better
81
-- versions
82

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

    
93
-- * JSON-related functions
94

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

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

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

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

    
125
-- | Annotate a Result with an ownership information
126
annotateResult :: String -> Result a -> Result a
127
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
128
annotateResult _ v = v
129

    
130
-- | Try to extract a key from a object with better error reporting
131
-- than fromObj
132
tryFromObj :: (J.JSON a) =>
133
              String -> [(String, J.JSValue)] -> String -> Result a
134
tryFromObj t o k = annotateResult t (fromObj k o)
135

    
136
-- | Small wrapper over readJSON.
137
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
138
fromJVal v =
139
    case J.readJSON v of
140
      J.Error s -> fail ("Cannot convert value " ++ show v ++ ", error: " ++ s)
141
      J.Ok x -> return x
142

    
143
-- | Converts a JSON value into a JSON object.
144
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
145
asJSObject (J.JSObject a) = return a
146
asJSObject _ = fail "not an object"
147

    
148
-- | Coneverts a list of JSON values into a list of JSON objects.
149
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
150
asObjectList = mapM asJSObject
151

    
152
-- * Parsing utility functions
153

    
154
-- | Parse results from readsPrec
155
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
156
parseChoices _ _ ((v, ""):[]) = return v
157
parseChoices name s ((_, e):[]) =
158
    fail $ name ++ ": leftover characters when parsing '"
159
           ++ s ++ "': '" ++ e ++ "'"
160
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
161

    
162
-- | Safe 'read' function returning data encapsulated in a Result.
163
tryRead :: (Monad m, Read a) => String -> String -> m a
164
tryRead name s = parseChoices name s $ reads s
165

    
166
-- | Format a table of strings to maintain consistent length
167
formatTable :: [[String]] -> [Bool] -> [[String]]
168
formatTable vals numpos =
169
    let vtrans = transpose vals  -- transpose, so that we work on rows
170
                                 -- rather than columns
171
        mlens = map (maximum . map length) vtrans
172
        expnd = map (\(flds, isnum, ml) ->
173
                         map (\val ->
174
                                  let delta = ml - length val
175
                                      filler = replicate delta ' '
176
                                  in if delta > 0
177
                                     then if isnum
178
                                          then filler ++ val
179
                                          else val ++ filler
180
                                     else val
181
                             ) flds
182
                    ) (zip3 vtrans numpos mlens)
183
   in transpose expnd