Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / JSON.hs @ 88b58ed6

History | View | Annotate | Download (10.3 kB)

1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
2
{-# OPTIONS_GHC -fno-warn-orphans #-}
3

    
4
{-| JSON utility functions. -}
5

    
6
{-
7

    
8
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
9

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

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

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

    
25
-}
26

    
27
module Ganeti.JSON
28
  ( fromJResult
29
  , readEitherString
30
  , JSRecord
31
  , loadJSArray
32
  , fromObj
33
  , maybeFromObj
34
  , fromObjWithDefault
35
  , fromKeyValue
36
  , fromJVal
37
  , jsonHead
38
  , getMaybeJsonHead
39
  , getMaybeJsonElem
40
  , asJSObject
41
  , asObjectList
42
  , tryFromObj
43
  , arrayMaybeFromJVal
44
  , tryArrayMaybeFromObj
45
  , toArray
46
  , optionalJSField
47
  , optFieldsToObj
48
  , HasStringRepr(..)
49
  , GenericContainer(..)
50
  , Container
51
  , MaybeForJSON(..)
52
  )
53
  where
54

    
55
import Control.DeepSeq
56
import Control.Monad (liftM)
57
import Data.Maybe (fromMaybe, catMaybes)
58
import qualified Data.Map as Map
59
import Text.Printf (printf)
60

    
61
import qualified Text.JSON as J
62
import Text.JSON.Pretty (pp_value)
63

    
64
-- Note: this module should not import any Ganeti-specific modules
65
-- beside BasicTypes, since it's used in THH which is used itself to
66
-- build many other modules.
67

    
68
import Ganeti.BasicTypes
69

    
70
-- * JSON-related functions
71

    
72
instance NFData J.JSValue where
73
  rnf J.JSNull           = ()
74
  rnf (J.JSBool b)       = rnf b
75
  rnf (J.JSRational b r) = rnf b `seq` rnf r
76
  rnf (J.JSString s)     = rnf $ J.fromJSString s
77
  rnf (J.JSArray a)      = rnf a
78
  rnf (J.JSObject o)     = rnf o
79

    
80
instance (NFData a) => NFData (J.JSObject a) where
81
  rnf = rnf . J.fromJSObject
82

    
83
-- | A type alias for a field of a JSRecord.
84
type JSField = (String, J.JSValue)
85

    
86
-- | A type alias for the list-based representation of J.JSObject.
87
type JSRecord = [JSField]
88

    
89
-- | Converts a JSON Result into a monadic value.
90
fromJResult :: Monad m => String -> J.Result a -> m a
91
fromJResult s (J.Error x) = fail (s ++ ": " ++ x)
92
fromJResult _ (J.Ok x) = return x
93

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

    
104
-- | Converts a JSON message into an array of JSON objects.
105
loadJSArray :: (Monad m)
106
               => String -- ^ Operation description (for error reporting)
107
               -> String -- ^ Input message
108
               -> m [J.JSObject J.JSValue]
109
loadJSArray s = fromJResult s . J.decodeStrict
110

    
111
-- | Helper function for missing-key errors
112
buildNoKeyError :: JSRecord -> String -> String
113
buildNoKeyError o k =
114
  printf "key '%s' not found, object contains only %s" k (show (map fst o))
115

    
116
-- | Reads the value of a key in a JSON object.
117
fromObj :: (J.JSON a, Monad m) => JSRecord -> String -> m a
118
fromObj o k =
119
  case lookup k o of
120
    Nothing -> fail $ buildNoKeyError o k
121
    Just val -> fromKeyValue k val
122

    
123
-- | Reads the value of an optional key in a JSON object. Missing
124
-- keys, or keys that have a \'null\' value, will be returned as
125
-- 'Nothing', otherwise we attempt deserialisation and return a 'Just'
126
-- value.
127
maybeFromObj :: (J.JSON a, Monad m) =>
128
                JSRecord -> String -> m (Maybe a)
129
maybeFromObj o k =
130
  case lookup k o of
131
    Nothing -> return Nothing
132
    -- a optional key with value JSNull is the same as missing, since
133
    -- we can't convert it meaningfully anyway to a Haskell type, and
134
    -- the Python code can emit 'null' for optional values (depending
135
    -- on usage), and finally our encoding rules treat 'null' values
136
    -- as 'missing'
137
    Just J.JSNull -> return Nothing
138
    Just val -> liftM Just (fromKeyValue k val)
139

    
140
-- | Reads the value of a key in a JSON object with a default if
141
-- missing. Note that both missing keys and keys with value \'null\'
142
-- will cause the default value to be returned.
143
fromObjWithDefault :: (J.JSON a, Monad m) =>
144
                      JSRecord -> String -> a -> m a
145
fromObjWithDefault o k d = liftM (fromMaybe d) $ maybeFromObj o k
146

    
147
arrayMaybeFromJVal :: (J.JSON a, Monad m) => J.JSValue -> m [Maybe a]
148
arrayMaybeFromJVal (J.JSArray xs) =
149
  mapM parse xs
150
    where
151
      parse J.JSNull = return Nothing
152
      parse x = liftM Just $ fromJVal x
153
arrayMaybeFromJVal v =
154
  fail $ "Expecting array, got '" ++ show (pp_value v) ++ "'"
155

    
156
-- | Reads an array of optional items
157
arrayMaybeFromObj :: (J.JSON a, Monad m) =>
158
                     JSRecord -> String -> m [Maybe a]
159
arrayMaybeFromObj o k =
160
  case lookup k o of
161
    Just a -> arrayMaybeFromJVal a
162
    _ -> fail $ buildNoKeyError o k
163

    
164
-- | Wrapper for arrayMaybeFromObj with better diagnostic
165
tryArrayMaybeFromObj :: (J.JSON a)
166
                     => String     -- ^ Textual "owner" in error messages
167
                     -> JSRecord   -- ^ The object array
168
                     -> String     -- ^ The desired key from the object
169
                     -> Result [Maybe a]
170
tryArrayMaybeFromObj t o = annotateResult t . arrayMaybeFromObj o
171

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

    
180
-- | Small wrapper over readJSON.
181
fromJVal :: (Monad m, J.JSON a) => J.JSValue -> m a
182
fromJVal v =
183
  case J.readJSON v of
184
    J.Error s -> fail ("Cannot convert value '" ++ show (pp_value v) ++
185
                       "', error: " ++ s)
186
    J.Ok x -> return x
187

    
188
-- | Helper function that returns Null or first element of the list.
189
jsonHead :: (J.JSON b) => [a] -> (a -> b) -> J.JSValue
190
jsonHead [] _ = J.JSNull
191
jsonHead (x:_) f = J.showJSON $ f x
192

    
193
-- | Helper for extracting Maybe values from a possibly empty list.
194
getMaybeJsonHead :: (J.JSON b) => [a] -> (a -> Maybe b) -> J.JSValue
195
getMaybeJsonHead [] _ = J.JSNull
196
getMaybeJsonHead (x:_) f = maybe J.JSNull J.showJSON (f x)
197

    
198
-- | Helper for extracting Maybe values from a list that might be too short.
199
getMaybeJsonElem :: (J.JSON b) => [a] -> Int -> (a -> Maybe b) -> J.JSValue
200
getMaybeJsonElem [] _ _ = J.JSNull
201
getMaybeJsonElem xs 0 f = getMaybeJsonHead xs f
202
getMaybeJsonElem (_:xs) n f
203
  | n < 0 = J.JSNull
204
  | otherwise = getMaybeJsonElem xs (n - 1) f
205

    
206
-- | Converts a JSON value into a JSON object.
207
asJSObject :: (Monad m) => J.JSValue -> m (J.JSObject J.JSValue)
208
asJSObject (J.JSObject a) = return a
209
asJSObject _ = fail "not an object"
210

    
211
-- | Coneverts a list of JSON values into a list of JSON objects.
212
asObjectList :: (Monad m) => [J.JSValue] -> m [J.JSObject J.JSValue]
213
asObjectList = mapM asJSObject
214

    
215
-- | Try to extract a key from an object with better error reporting
216
-- than fromObj.
217
tryFromObj :: (J.JSON a) =>
218
              String     -- ^ Textual "owner" in error messages
219
           -> JSRecord   -- ^ The object array
220
           -> String     -- ^ The desired key from the object
221
           -> Result a
222
tryFromObj t o = annotateResult t . fromObj o
223

    
224
-- | Ensure a given JSValue is actually a JSArray.
225
toArray :: (Monad m) => J.JSValue -> m [J.JSValue]
226
toArray (J.JSArray arr) = return arr
227
toArray o =
228
  fail $ "Invalid input, expected array but got " ++ show (pp_value o)
229

    
230
-- | Creates a Maybe JSField. If the value string is Nothing, the JSField
231
-- will be Nothing as well.
232
optionalJSField :: (J.JSON a) => String -> Maybe a -> Maybe JSField
233
optionalJSField name (Just value) = Just (name, J.showJSON value)
234
optionalJSField _ Nothing = Nothing
235

    
236
-- | Creates an object with all the non-Nothing fields of the given list.
237
optFieldsToObj :: [Maybe JSField] -> J.JSValue
238
optFieldsToObj = J.makeObj . catMaybes
239

    
240
-- * Container type (special type for JSON serialisation)
241

    
242
-- | Class of types that can be converted from Strings. This is
243
-- similar to the 'Read' class, but it's using a different
244
-- serialisation format, so we have to define a separate class. Mostly
245
-- useful for custom key types in JSON dictionaries, which have to be
246
-- backed by strings.
247
class HasStringRepr a where
248
  fromStringRepr :: (Monad m) => String -> m a
249
  toStringRepr :: a -> String
250

    
251
-- | Trivial instance 'HasStringRepr' for 'String'.
252
instance HasStringRepr String where
253
  fromStringRepr = return
254
  toStringRepr = id
255

    
256
-- | The container type, a wrapper over Data.Map
257
newtype GenericContainer a b =
258
  GenericContainer { fromContainer :: Map.Map a b }
259
  deriving (Show, Eq)
260

    
261
instance (NFData a, NFData b) => NFData (GenericContainer a b) where
262
  rnf = rnf . Map.toList . fromContainer
263

    
264
-- | Type alias for string keys.
265
type Container = GenericContainer String
266

    
267
-- | Container loader.
268
readContainer :: (Monad m, HasStringRepr a, Ord a, J.JSON b) =>
269
                 J.JSObject J.JSValue -> m (GenericContainer a b)
270
readContainer obj = do
271
  let kjvlist = J.fromJSObject obj
272
  kalist <- mapM (\(k, v) -> do
273
                    k' <- fromStringRepr k
274
                    v' <- fromKeyValue k v
275
                    return (k', v')) kjvlist
276
  return $ GenericContainer (Map.fromList kalist)
277

    
278
{-# ANN showContainer "HLint: ignore Use ***" #-}
279
-- | Container dumper.
280
showContainer :: (HasStringRepr a, J.JSON b) =>
281
                 GenericContainer a b -> J.JSValue
282
showContainer =
283
  J.makeObj . map (\(k, v) -> (toStringRepr k, J.showJSON v)) .
284
  Map.toList . fromContainer
285

    
286
instance (HasStringRepr a, Ord a, J.JSON b) =>
287
         J.JSON (GenericContainer a b) where
288
  showJSON = showContainer
289
  readJSON (J.JSObject o) = readContainer o
290
  readJSON v = fail $ "Failed to load container, expected object but got "
291
               ++ show (pp_value v)
292

    
293
-- | A Maybe newtype that allows for serialization more appropriate to the
294
-- semantics of Maybe and JSON in our calls. Does not produce needless
295
-- and confusing dictionaries.
296
newtype MaybeForJSON a = MaybeForJSON { unMaybeForJSON :: Maybe a }
297
instance (J.JSON a) => J.JSON (MaybeForJSON a) where
298
  readJSON = J.readJSON
299
  showJSON (MaybeForJSON (Just x)) = J.showJSON x
300
  showJSON (MaybeForJSON Nothing)  = J.JSNull