Utils.hs 7 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
{-| Utility functions -}

Iustin Pop's avatar
Iustin Pop committed
3
4
{-

Iustin Pop's avatar
Iustin Pop committed
5
Copyright (C) 2009, 2010 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.

-}

24
25
26
module Ganeti.HTools.Utils
    (
      debug
Iustin Pop's avatar
Iustin Pop committed
27
28
    , debugFn
    , debugXy
29
30
    , sepSplit
    , varianceCoeff
31
    , commaJoin
32
33
34
    , readEitherString
    , loadJSArray
    , fromObj
35
    , maybeFromObj
36
37
    , tryFromObj
    , fromJVal
Iustin Pop's avatar
Iustin Pop committed
38
39
    , asJSObject
    , asObjectList
40
    , fromJResult
41
    , tryRead
42
    , formatTable
43
    , annotateResult
Iustin Pop's avatar
Iustin Pop committed
44
    , defaultGroupID
45
    ) where
Iustin Pop's avatar
Iustin Pop committed
46

47
import Control.Monad (liftM)
48
import Data.List
49
import qualified Text.JSON as J
50
import Text.Printf (printf)
Iustin Pop's avatar
Iustin Pop committed
51
52
53

import Debug.Trace

54
55
import Ganeti.HTools.Types

Iustin Pop's avatar
Iustin Pop committed
56
57
-- * Debug functions

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

Iustin Pop's avatar
Iustin Pop committed
62
63
64
65
66
67
68
69
-- | Displays a modified form of the second parameter before returning it
debugFn :: Show b => (a -> b) -> a -> a
debugFn fn x = debug (fn x) `seq` x

-- | Show the first parameter before returning the second one
debugXy :: Show a => a -> b -> b
debugXy a b = debug a `seq` b

Iustin Pop's avatar
Iustin Pop committed
70
-- * Miscelaneous
Iustin Pop's avatar
Iustin Pop committed
71

Iustin Pop's avatar
Iustin Pop committed
72
73
74
75
-- | Comma-join a string list.
commaJoin :: [String] -> String
commaJoin = intercalate ","

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

Iustin Pop's avatar
Iustin Pop committed
86
87
-- * Mathematical functions

88
89
-- Simple and slow statistical functions, please replace with better
-- versions
Iustin Pop's avatar
Iustin Pop committed
90

91
-- | Our modified standard deviation function (not, it's not the variance)
Iustin Pop's avatar
Iustin Pop committed
92
varianceCoeff :: [Double] -> Double
93
varianceCoeff lst =
94
95
96
97
98
99
100
101
102
103
104
105
  -- first, calculate the list length and sum lst in a single step,
  -- for performance reasons
  let (ll', sx) = foldl' (\(rl, rs) e ->
                           let rl' = rl + 1
                               rs' = rs + e
                           in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
      ll = fromIntegral ll'::Double
      mv = sx / ll
      av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
      bv = sqrt (av / ll) -- stddev
      cv = bv / ll        -- standard deviation divided by list length
  in cv
Iustin Pop's avatar
Iustin Pop committed
106

Iustin Pop's avatar
Iustin Pop committed
107
108
109
-- * JSON-related functions

-- | Converts a JSON Result into a monadic value.
110
111
112
fromJResult :: Monad m => String -> J.Result a -> m a
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
fromJResult _ (J.Ok x) = return x
Iustin Pop's avatar
Iustin Pop committed
113

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

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

131
-- | Reads the value of a key in a JSON object.
132
fromObj :: (J.JSON a, Monad m) => String -> [(String, J.JSValue)] -> m a
133
fromObj k o =
134
    case lookup k o of
Iustin Pop's avatar
Iustin Pop committed
135
      Nothing -> fail $ printf "key '%s' not found in %s" k (show o)
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
      Just val -> fromKeyValue k val

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

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

154
155
156
157
158
159
160
161
162
-- | Annotate a Result with an ownership information
annotateResult :: String -> Result a -> Result a
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
annotateResult _ v = v

-- | Try to extract a key from a object with better error reporting
-- than fromObj
tryFromObj :: (J.JSON a) =>
              String -> [(String, J.JSValue)] -> String -> Result a
Iustin Pop's avatar
Iustin Pop committed
163
tryFromObj t o k = annotateResult t (fromObj k o)
164
165
166
167
168
169
170
171

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

Iustin Pop's avatar
Iustin Pop committed
172
-- | Converts a JSON value into a JSON object.
173
174
175
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
asJSObject (J.JSObject a) = return a
asJSObject _ = fail "not an object"
176

Iustin Pop's avatar
Iustin Pop committed
177
-- | Coneverts a list of JSON values into a list of JSON objects.
178
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
Iustin Pop's avatar
Iustin Pop committed
179
asObjectList = mapM asJSObject
180
181
182
183
184
185
186
187
188
189
190
191
192
193

-- * Parsing utility functions

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

-- | Safe 'read' function returning data encapsulated in a Result.
tryRead :: (Monad m, Read a) => String -> String -> m a
tryRead name s = parseChoices name s $ reads s
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212

-- | Format a table of strings to maintain consistent length
formatTable :: [[String]] -> [Bool] -> [[String]]
formatTable vals numpos =
    let vtrans = transpose vals  -- transpose, so that we work on rows
                                 -- rather than columns
        mlens = map (maximum . map length) vtrans
        expnd = map (\(flds, isnum, ml) ->
                         map (\val ->
                                  let delta = ml - length val
                                      filler = replicate delta ' '
                                  in if delta > 0
                                     then if isnum
                                          then filler ++ val
                                          else val ++ filler
                                     else val
                             ) flds
                    ) (zip3 vtrans numpos mlens)
   in transpose expnd
Iustin Pop's avatar
Iustin Pop committed
213

Iustin Pop's avatar
Iustin Pop committed
214
215
216
-- | Default group UUID (just a string, not a real UUID)
defaultGroupID :: GroupID
defaultGroupID = "00000000-0000-0000-0000-000000000000"