Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / Rpc.hs @ 1ca709c1

History | View | Annotate | Download (15.2 kB)

1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,
2
  BangPatterns, TemplateHaskell #-}
3

    
4
{-| Implementation of the RPC client.
5

    
6
-}
7

    
8
{-
9

    
10
Copyright (C) 2012, 2013 Google Inc.
11

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

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

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

    
27
-}
28

    
29
module Ganeti.Rpc
30
  ( RpcCall
31
  , Rpc
32
  , RpcError(..)
33
  , ERpcError
34
  , explainRpcError
35
  , executeRpcCall
36

    
37
  , rpcCallName
38
  , rpcCallTimeout
39
  , rpcCallData
40
  , rpcCallAcceptOffline
41

    
42
  , rpcResultFill
43

    
44
  , InstanceInfo(..)
45
  , RpcCallInstanceInfo(..)
46
  , RpcResultInstanceInfo(..)
47

    
48
  , RpcCallAllInstancesInfo(..)
49
  , RpcResultAllInstancesInfo(..)
50

    
51
  , RpcCallInstanceList(..)
52
  , RpcResultInstanceList(..)
53

    
54
  , HvInfo(..)
55
  , VgInfo(..)
56
  , RpcCallNodeInfo(..)
57
  , RpcResultNodeInfo(..)
58

    
59
  , RpcCallVersion(..)
60
  , RpcResultVersion(..)
61

    
62
  , StorageField(..)
63
  , RpcCallStorageList(..)
64
  , RpcResultStorageList(..)
65

    
66
  , RpcCallTestDelay(..)
67
  , RpcResultTestDelay(..)
68

    
69
  , rpcTimeoutFromRaw -- FIXME: Not used anywhere
70
  ) where
71

    
72
import Control.Arrow (second)
73
import qualified Data.Map as Map
74
import Data.Maybe (fromMaybe)
75
import qualified Text.JSON as J
76
import Text.JSON.Pretty (pp_value)
77

    
78
import Network.Curl
79
import qualified Ganeti.Path as P
80

    
81
import qualified Ganeti.Constants as C
82
import Ganeti.Objects
83
import Ganeti.THH
84
import Ganeti.Types
85
import Ganeti.Compat
86

    
87
-- * Base RPC functionality and types
88

    
89
-- | The curl options used for RPC.
90
curlOpts :: [CurlOption]
91
curlOpts = [ CurlFollowLocation False
92
           , CurlSSLVerifyHost 0
93
           , CurlSSLVerifyPeer True
94
           , CurlSSLCertType "PEM"
95
           , CurlSSLKeyType "PEM"
96
           , CurlConnectTimeout (fromIntegral C.rpcConnectTimeout)
97
           ]
98

    
99
-- | Data type for RPC error reporting.
100
data RpcError
101
  = CurlLayerError Node String
102
  | JsonDecodeError String
103
  | RpcResultError String
104
  | OfflineNodeError Node
105
  deriving (Show, Eq)
106

    
107
-- | Provide explanation to RPC errors.
108
explainRpcError :: RpcError -> String
109
explainRpcError (CurlLayerError node code) =
110
    "Curl error for " ++ nodeName node ++ ", " ++ code
111
explainRpcError (JsonDecodeError msg) =
112
    "Error while decoding JSON from HTTP response: " ++ msg
113
explainRpcError (RpcResultError msg) =
114
    "Error reponse received from RPC server: " ++ msg
115
explainRpcError (OfflineNodeError node) =
116
    "Node " ++ nodeName node ++ " is marked as offline"
117

    
118
type ERpcError = Either RpcError
119

    
120
-- | Basic timeouts for RPC calls.
121
$(declareIADT "RpcTimeout"
122
  [ ( "Urgent",    'C.rpcTmoUrgent )
123
  , ( "Fast",      'C.rpcTmoFast )
124
  , ( "Normal",    'C.rpcTmoNormal )
125
  , ( "Slow",      'C.rpcTmoSlow )
126
  , ( "FourHours", 'C.rpcTmo4hrs )
127
  , ( "OneDay",    'C.rpcTmo1day )
128
  ])
129

    
130
-- | A generic class for RPC calls.
131
class (J.JSON a) => RpcCall a where
132
  -- | Give the (Python) name of the procedure.
133
  rpcCallName :: a -> String
134
  -- | Calculate the timeout value for the call execution.
135
  rpcCallTimeout :: a -> Int
136
  -- | Prepare arguments of the call to be send as POST.
137
  rpcCallData :: Node -> a -> String
138
  -- | Whether we accept offline nodes when making a call.
139
  rpcCallAcceptOffline :: a -> Bool
140

    
141
-- | Generic class that ensures matching RPC call with its respective
142
-- result.
143
class (RpcCall a, J.JSON b) => Rpc a b  | a -> b, b -> a where
144
  -- | Create a result based on the received HTTP response.
145
  rpcResultFill :: a -> J.JSValue -> ERpcError b
146

    
147
-- | Http Request definition.
148
data HttpClientRequest = HttpClientRequest
149
  { requestTimeout :: Int
150
  , requestUrl :: String
151
  , requestPostData :: String
152
  }
153

    
154
-- | Execute the request and return the result as a plain String. When
155
-- curl reports an error, we propagate it.
156
executeHttpRequest :: Node -> ERpcError HttpClientRequest
157
                   -> IO (ERpcError String)
158

    
159
executeHttpRequest _ (Left rpc_err) = return $ Left rpc_err
160
executeHttpRequest node (Right request) = do
161
  cert_file <- P.nodedCertFile
162
  let reqOpts = [ CurlTimeout (fromIntegral $ requestTimeout request)
163
                , CurlPostFields [requestPostData request]
164
                , CurlSSLCert cert_file
165
                , CurlSSLKey cert_file
166
                , CurlCAInfo cert_file
167
                ]
168
      url = requestUrl request
169
  -- FIXME: This is very similar to getUrl in Htools/Rapi.hs
170
  (code, !body) <- curlGetString url $ curlOpts ++ reqOpts
171
  return $ case code of
172
             CurlOK -> Right body
173
             _ -> Left $ CurlLayerError node (show code)
174

    
175
-- | Prepare url for the HTTP request.
176
prepareUrl :: (RpcCall a) => Node -> a -> String
177
prepareUrl node call =
178
  let node_ip = nodePrimaryIp node
179
      port = snd C.daemonsPortsGanetiNoded
180
      path_prefix = "https://" ++ node_ip ++ ":" ++ show port
181
  in path_prefix ++ "/" ++ rpcCallName call
182

    
183
-- | Create HTTP request for a given node provided it is online,
184
-- otherwise create empty response.
185
prepareHttpRequest ::  (RpcCall a) => Node -> a
186
                   -> ERpcError HttpClientRequest
187
prepareHttpRequest node call
188
  | rpcCallAcceptOffline call || not (nodeOffline node) =
189
      Right HttpClientRequest { requestTimeout = rpcCallTimeout call
190
                              , requestUrl = prepareUrl node call
191
                              , requestPostData = rpcCallData node call
192
                              }
193
  | otherwise = Left $ OfflineNodeError node
194

    
195
-- | Parse a result based on the received HTTP response.
196
parseHttpResponse :: (Rpc a b) => a -> ERpcError String -> ERpcError b
197
parseHttpResponse _ (Left err) = Left err
198
parseHttpResponse call (Right res) =
199
  case J.decode res of
200
    J.Error val -> Left $ JsonDecodeError val
201
    J.Ok (True, res'') -> rpcResultFill call res''
202
    J.Ok (False, jerr) -> case jerr of
203
       J.JSString msg -> Left $ RpcResultError (J.fromJSString msg)
204
       _ -> Left . JsonDecodeError $ show (pp_value jerr)
205

    
206
-- | Execute RPC call for a sigle node.
207
executeSingleRpcCall :: (Rpc a b) => Node -> a -> IO (Node, ERpcError b)
208
executeSingleRpcCall node call = do
209
  let request = prepareHttpRequest node call
210
  response <- executeHttpRequest node request
211
  let result = parseHttpResponse call response
212
  return (node, result)
213

    
214
-- | Execute RPC call for many nodes in parallel.
215
executeRpcCall :: (Rpc a b) => [Node] -> a -> IO [(Node, ERpcError b)]
216
executeRpcCall nodes call =
217
  sequence $ parMap rwhnf (uncurry executeSingleRpcCall)
218
               (zip nodes $ repeat call)
219

    
220
-- | Helper function that is used to read dictionaries of values.
221
sanitizeDictResults :: [(String, J.Result a)] -> ERpcError [(String, a)]
222
sanitizeDictResults =
223
  foldr sanitize1 (Right [])
224
  where
225
    sanitize1 _ (Left e) = Left e
226
    sanitize1 (_, J.Error e) _ = Left $ JsonDecodeError e
227
    sanitize1 (name, J.Ok v) (Right res) = Right $ (name, v) : res
228

    
229
-- | Helper function to tranform JSON Result to Either RpcError b.
230
-- Note: For now we really only use it for b s.t. Rpc c b for some c
231
fromJResultToRes :: J.Result a -> (a -> b) -> ERpcError b
232
fromJResultToRes (J.Error v) _ = Left $ JsonDecodeError v
233
fromJResultToRes (J.Ok v) f = Right $ f v
234

    
235
-- | Helper function transforming JSValue to Rpc result type.
236
fromJSValueToRes :: (J.JSON a) => J.JSValue -> (a -> b) -> ERpcError b
237
fromJSValueToRes val = fromJResultToRes (J.readJSON val)
238

    
239
-- * RPC calls and results
240

    
241
-- ** Instance info
242

    
243
-- | InstanceInfo
244
--   Returns information about a single instance.
245

    
246
$(buildObject "RpcCallInstanceInfo" "rpcCallInstInfo"
247
  [ simpleField "instance" [t| String |]
248
  , simpleField "hname" [t| Hypervisor |]
249
  ])
250

    
251
$(buildObject "InstanceInfo" "instInfo"
252
  [ simpleField "memory" [t| Int|]
253
  , simpleField "state"  [t| String |] -- It depends on hypervisor :(
254
  , simpleField "vcpus"  [t| Int |]
255
  , simpleField "time"   [t| Int |]
256
  ])
257

    
258
-- This is optional here because the result may be empty if instance is
259
-- not on a node - and this is not considered an error.
260
$(buildObject "RpcResultInstanceInfo" "rpcResInstInfo"
261
  [ optionalField $ simpleField "inst_info" [t| InstanceInfo |]])
262

    
263
instance RpcCall RpcCallInstanceInfo where
264
  rpcCallName _          = "instance_info"
265
  rpcCallTimeout _       = rpcTimeoutToRaw Urgent
266
  rpcCallAcceptOffline _ = False
267
  rpcCallData _ call     = J.encode
268
    ( rpcCallInstInfoInstance call
269
    , rpcCallInstInfoHname call
270
    )
271

    
272
instance Rpc RpcCallInstanceInfo RpcResultInstanceInfo where
273
  rpcResultFill _ res =
274
    case res of
275
      J.JSObject res' ->
276
        case J.fromJSObject res' of
277
          [] -> Right $ RpcResultInstanceInfo Nothing
278
          _ -> fromJSValueToRes res (RpcResultInstanceInfo . Just)
279
      _ -> Left $ JsonDecodeError
280
           ("Expected JSObject, got " ++ show (pp_value res))
281

    
282
-- ** AllInstancesInfo
283

    
284
-- | AllInstancesInfo
285
--   Returns information about all running instances on the given nodes
286
$(buildObject "RpcCallAllInstancesInfo" "rpcCallAllInstInfo"
287
  [ simpleField "hypervisors" [t| [Hypervisor] |] ])
288

    
289
$(buildObject "RpcResultAllInstancesInfo" "rpcResAllInstInfo"
290
  [ simpleField "instances" [t| [(String, InstanceInfo)] |] ])
291

    
292
instance RpcCall RpcCallAllInstancesInfo where
293
  rpcCallName _          = "all_instances_info"
294
  rpcCallTimeout _       = rpcTimeoutToRaw Urgent
295
  rpcCallAcceptOffline _ = False
296
  rpcCallData _ call     = J.encode [rpcCallAllInstInfoHypervisors call]
297

    
298
instance Rpc RpcCallAllInstancesInfo RpcResultAllInstancesInfo where
299
  -- FIXME: Is there a simpler way to do it?
300
  rpcResultFill _ res =
301
    case res of
302
      J.JSObject res' ->
303
        let res'' = map (second J.readJSON) (J.fromJSObject res')
304
                        :: [(String, J.Result InstanceInfo)] in
305
        case sanitizeDictResults res'' of
306
          Left err -> Left err
307
          Right insts -> Right $ RpcResultAllInstancesInfo insts
308
      _ -> Left $ JsonDecodeError
309
           ("Expected JSObject, got " ++ show (pp_value res))
310

    
311
-- ** InstanceList
312

    
313
-- | InstanceList
314
-- Returns the list of running instances on the given nodes.
315
$(buildObject "RpcCallInstanceList" "rpcCallInstList"
316
  [ simpleField "hypervisors" [t| [Hypervisor] |] ])
317

    
318
$(buildObject "RpcResultInstanceList" "rpcResInstList"
319
  [ simpleField "instances" [t| [String] |] ])
320

    
321
instance RpcCall RpcCallInstanceList where
322
  rpcCallName _          = "instance_list"
323
  rpcCallTimeout _       = rpcTimeoutToRaw Urgent
324
  rpcCallAcceptOffline _ = False
325
  rpcCallData _ call     = J.encode [rpcCallInstListHypervisors call]
326

    
327
instance Rpc RpcCallInstanceList RpcResultInstanceList where
328
  rpcResultFill _ res = fromJSValueToRes res RpcResultInstanceList
329

    
330
-- ** NodeInfo
331

    
332
-- | NodeInfo
333
-- Return node information.
334
$(buildObject "RpcCallNodeInfo" "rpcCallNodeInfo"
335
  [ simpleField "volume_groups" [t| [String] |]
336
  , simpleField "hypervisors" [t| [Hypervisor] |]
337
  , simpleField "exclusive_storage" [t| Map.Map String Bool |]
338
  ])
339

    
340
$(buildObject "VgInfo" "vgInfo"
341
  [ simpleField "name" [t| String |]
342
  , optionalField $ simpleField "vg_free" [t| Int |]
343
  , optionalField $ simpleField "vg_size" [t| Int |]
344
  ])
345

    
346
-- | We only provide common fields as described in hv_base.py.
347
$(buildObject "HvInfo" "hvInfo"
348
  [ simpleField "memory_total" [t| Int |]
349
  , simpleField "memory_free" [t| Int |]
350
  , simpleField "memory_dom0" [t| Int |]
351
  , simpleField "cpu_total" [t| Int |]
352
  , simpleField "cpu_nodes" [t| Int |]
353
  , simpleField "cpu_sockets" [t| Int |]
354
  ])
355

    
356
$(buildObject "RpcResultNodeInfo" "rpcResNodeInfo"
357
  [ simpleField "boot_id" [t| String |]
358
  , simpleField "vg_info" [t| [VgInfo] |]
359
  , simpleField "hv_info" [t| [HvInfo] |]
360
  ])
361

    
362
instance RpcCall RpcCallNodeInfo where
363
  rpcCallName _          = "node_info"
364
  rpcCallTimeout _       = rpcTimeoutToRaw Urgent
365
  rpcCallAcceptOffline _ = False
366
  rpcCallData n call     = J.encode
367
    ( rpcCallNodeInfoVolumeGroups call
368
    , rpcCallNodeInfoHypervisors call
369
    , fromMaybe (error $ "Programmer error: missing parameter for node named "
370
                         ++ nodeName n)
371
                $ Map.lookup (nodeName n) (rpcCallNodeInfoExclusiveStorage call)
372
    )
373

    
374
instance Rpc RpcCallNodeInfo RpcResultNodeInfo where
375
  rpcResultFill _ res =
376
    fromJSValueToRes res (\(b, vg, hv) -> RpcResultNodeInfo b vg hv)
377

    
378
-- ** Version
379

    
380
-- | Version
381
-- Query node version.
382
-- Note: We can't use THH as it does not know what to do with empty dict
383
data RpcCallVersion = RpcCallVersion {}
384
  deriving (Show, Eq)
385

    
386
instance J.JSON RpcCallVersion where
387
  showJSON _ = J.JSNull
388
  readJSON J.JSNull = return RpcCallVersion
389
  readJSON _ = fail "Unable to read RpcCallVersion"
390

    
391
$(buildObject "RpcResultVersion" "rpcResultVersion"
392
  [ simpleField "version" [t| Int |]
393
  ])
394

    
395
instance RpcCall RpcCallVersion where
396
  rpcCallName _          = "version"
397
  rpcCallTimeout _       = rpcTimeoutToRaw Urgent
398
  rpcCallAcceptOffline _ = True
399
  rpcCallData _          = J.encode
400

    
401
instance Rpc RpcCallVersion RpcResultVersion where
402
  rpcResultFill _ res = fromJSValueToRes res RpcResultVersion
403

    
404
-- ** StorageList
405

    
406
-- | StorageList
407

    
408
-- FIXME: This may be moved to Objects
409
$(declareSADT "StorageField"
410
  [ ( "SFUsed",        'C.sfUsed)
411
  , ( "SFName",        'C.sfName)
412
  , ( "SFAllocatable", 'C.sfAllocatable)
413
  , ( "SFFree",        'C.sfFree)
414
  , ( "SFSize",        'C.sfSize)
415
  ])
416
$(makeJSONInstance ''StorageField)
417

    
418
$(buildObject "RpcCallStorageList" "rpcCallStorageList"
419
  [ simpleField "su_name" [t| StorageType |]
420
  , simpleField "su_args" [t| [String] |]
421
  , simpleField "name"    [t| String |]
422
  , simpleField "fields"  [t| [StorageField] |]
423
  ])
424

    
425
-- FIXME: The resulting JSValues should have types appropriate for their
426
-- StorageField value: Used -> Bool, Name -> String etc
427
$(buildObject "RpcResultStorageList" "rpcResStorageList"
428
  [ simpleField "storage" [t| [[(StorageField, J.JSValue)]] |] ])
429

    
430
instance RpcCall RpcCallStorageList where
431
  rpcCallName _          = "storage_list"
432
  rpcCallTimeout _       = rpcTimeoutToRaw Normal
433
  rpcCallAcceptOffline _ = False
434
  rpcCallData _ call     = J.encode
435
    ( rpcCallStorageListSuName call
436
    , rpcCallStorageListSuArgs call
437
    , rpcCallStorageListName call
438
    , rpcCallStorageListFields call
439
    )
440

    
441
instance Rpc RpcCallStorageList RpcResultStorageList where
442
  rpcResultFill call res =
443
    let sfields = rpcCallStorageListFields call in
444
    fromJSValueToRes res (RpcResultStorageList . map (zip sfields))
445

    
446
-- ** TestDelay
447

    
448

    
449
-- | Call definition for test delay.
450
$(buildObject "RpcCallTestDelay" "rpcCallTestDelay"
451
  [ simpleField "duration" [t| Double |]
452
  ])
453

    
454
-- | Result definition for test delay.
455
data RpcResultTestDelay = RpcResultTestDelay
456
                          deriving Show
457

    
458
-- | Custom JSON instance for null result.
459
instance J.JSON RpcResultTestDelay where
460
  showJSON _        = J.JSNull
461
  readJSON J.JSNull = return RpcResultTestDelay
462
  readJSON _        = fail "Unable to read RpcResultTestDelay"
463

    
464
instance RpcCall RpcCallTestDelay where
465
  rpcCallName _          = "test_delay"
466
  rpcCallTimeout         = ceiling . (+ 5) . rpcCallTestDelayDuration
467
  rpcCallAcceptOffline _ = False
468
  rpcCallData _ call     = J.encode [rpcCallTestDelayDuration call]
469

    
470
instance Rpc RpcCallTestDelay RpcResultTestDelay where
471
  rpcResultFill _ res = fromJSValueToRes res id