Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / Rpc.hs @ 9c0a27d0

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 String
102
  | JsonDecodeError String
103
  | RpcResultError String
104
  | OfflineNodeError
105
  deriving (Show, Eq)
106

    
107
-- | Provide explanation to RPC errors.
108
explainRpcError :: RpcError -> String
109
explainRpcError (CurlLayerError code) =
110
    "Curl error:" ++ 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 =
116
    "Node is marked 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
  { requestUrl  :: String       -- ^ The actual URL for the node endpoint
150
  , requestData :: String       -- ^ The arguments for the call
151
  , requestOpts :: [CurlOption] -- ^ The various curl options
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 :: ERpcError HttpClientRequest -> IO (ERpcError String)
157
executeHttpRequest (Left rpc_err) = return $ Left rpc_err
158
executeHttpRequest (Right request) = do
159
  let reqOpts = CurlPostFields [requestData request]:requestOpts request
160
      url = requestUrl request
161
  -- FIXME: This is very similar to getUrl in Htools/Rapi.hs
162
  (code, !body) <- curlGetString url $ curlOpts ++ reqOpts
163
  return $ case code of
164
             CurlOK -> Right body
165
             _ -> Left $ CurlLayerError (show code)
166

    
167
-- | Prepare url for the HTTP request.
168
prepareUrl :: (RpcCall a) => Node -> a -> String
169
prepareUrl node call =
170
  let node_ip = nodePrimaryIp node
171
      port = snd C.daemonsPortsGanetiNoded
172
      path_prefix = "https://" ++ node_ip ++ ":" ++ show port
173
  in path_prefix ++ "/" ++ rpcCallName call
174

    
175
-- | Create HTTP request for a given node provided it is online,
176
-- otherwise create empty response.
177
prepareHttpRequest :: (RpcCall a) => [CurlOption] -> Node -> a
178
                   -> ERpcError HttpClientRequest
179
prepareHttpRequest opts node call
180
  | rpcCallAcceptOffline call || not (nodeOffline node) =
181
      Right HttpClientRequest { requestUrl  = prepareUrl node call
182
                              , requestData = rpcCallData node call
183
                              , requestOpts = opts ++ curlOpts
184
                              }
185
  | otherwise = Left OfflineNodeError
186

    
187
-- | Parse a result based on the received HTTP response.
188
parseHttpResponse :: (Rpc a b) => a -> ERpcError String -> ERpcError b
189
parseHttpResponse _ (Left err) = Left err
190
parseHttpResponse call (Right res) =
191
  case J.decode res of
192
    J.Error val -> Left $ JsonDecodeError val
193
    J.Ok (True, res'') -> rpcResultFill call res''
194
    J.Ok (False, jerr) -> case jerr of
195
       J.JSString msg -> Left $ RpcResultError (J.fromJSString msg)
196
       _ -> Left . JsonDecodeError $ show (pp_value jerr)
197

    
198
-- | Execute RPC call for a sigle node.
199
executeSingleRpcCall :: (Rpc a b) =>
200
                        [CurlOption] -> Node -> a -> IO (Node, ERpcError b)
201
executeSingleRpcCall opts node call = do
202
  let request = prepareHttpRequest opts node call
203
  response <- executeHttpRequest request
204
  let result = parseHttpResponse call response
205
  return (node, result)
206

    
207
-- | Execute RPC call for many nodes in parallel.
208
executeRpcCall :: (Rpc a b) => [Node] -> a -> IO [(Node, ERpcError b)]
209
executeRpcCall nodes call = do
210
  cert_file <- P.nodedCertFile
211
  let opts = [ CurlTimeout (fromIntegral $ rpcCallTimeout call)
212
             , CurlSSLCert cert_file
213
             , CurlSSLKey cert_file
214
             , CurlCAInfo cert_file
215
             ]
216
  sequence $ parMap rwhnf (\n -> executeSingleRpcCall opts n call) nodes
217

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

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

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

    
237
-- * RPC calls and results
238

    
239
-- ** Instance info
240

    
241
-- | InstanceInfo
242
--   Returns information about a single instance.
243

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

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

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

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

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

    
280
-- ** AllInstancesInfo
281

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

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

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

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

    
309
-- ** InstanceList
310

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

    
316
$(buildObject "RpcResultInstanceList" "rpcResInstList"
317
  [ simpleField "instances" [t| [String] |] ])
318

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

    
325
instance Rpc RpcCallInstanceList RpcResultInstanceList where
326
  rpcResultFill _ res = fromJSValueToRes res RpcResultInstanceList
327

    
328
-- ** NodeInfo
329

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

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

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

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

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

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

    
376
-- ** Version
377

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

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

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

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

    
399
instance Rpc RpcCallVersion RpcResultVersion where
400
  rpcResultFill _ res = fromJSValueToRes res RpcResultVersion
401

    
402
-- ** StorageList
403

    
404
-- | StorageList
405

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

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

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

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

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

    
444
-- ** TestDelay
445

    
446

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

    
452
-- | Result definition for test delay.
453
data RpcResultTestDelay = RpcResultTestDelay
454
                          deriving Show
455

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

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

    
468
instance Rpc RpcCallTestDelay RpcResultTestDelay where
469
  rpcResultFill _ res = fromJSValueToRes res id