Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / Rpc.hs @ 96dad12d

History | View | Annotate | Download (7.2 kB)

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

    
4
{-| Implementation of the RPC client.
5

    
6
-}
7

    
8
{-
9

    
10
Copyright (C) 2012 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
  , RpcResult
32
  , Rpc
33
  , RpcError(..)
34
  , executeRpcCall
35

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

    
41
  , rpcResultFill
42

    
43
  , InstanceInfo(..)
44
  , RpcCallAllInstancesInfo(..)
45
  , RpcResultAllInstancesInfo(..)
46

    
47
  , rpcTimeoutFromRaw -- FIXME: Not used anywhere
48
  ) where
49

    
50
import qualified Text.JSON as J
51
import Text.JSON (makeObj)
52

    
53
#ifndef NO_CURL
54
import Network.Curl
55
#endif
56

    
57
import qualified Ganeti.Constants as C
58
import Ganeti.Objects
59
import Ganeti.THH
60
import Ganeti.HTools.Compat
61
import Ganeti.HTools.JSON
62

    
63
#ifndef NO_CURL
64
-- | The curl options used for RPC.
65
curlOpts :: [CurlOption]
66
curlOpts = [ CurlFollowLocation False
67
           , CurlCAInfo C.nodedCertFile
68
           , CurlSSLVerifyHost 0
69
           , CurlSSLVerifyPeer True
70
           , CurlSSLCertType "PEM"
71
           , CurlSSLCert C.nodedCertFile
72
           , CurlSSLKeyType "PEM"
73
           , CurlSSLKey C.nodedCertFile
74
           , CurlConnectTimeout (fromIntegral C.rpcConnectTimeout)
75
           ]
76
#endif
77

    
78
-- | Data type for RPC error reporting.
79
data RpcError
80
  = CurlDisabledError
81
  | CurlLayerError Node String
82
  | JsonDecodeError String
83
  | OfflineNodeError Node
84
  deriving Eq
85

    
86
instance Show RpcError where
87
  show CurlDisabledError =
88
    "RPC/curl backend disabled at compile time"
89
  show (CurlLayerError node code) =
90
    "Curl error for " ++ nodeName node ++ ", error " ++ code
91
  show (JsonDecodeError msg) =
92
    "Error while decoding JSON from HTTP response " ++ msg
93
  show (OfflineNodeError node) =
94
    "Node " ++ nodeName node ++ " is marked as offline"
95

    
96
rpcErrorJsonReport :: (Monad m) => J.Result a -> m (Either RpcError a)
97
rpcErrorJsonReport (J.Error x) = return $ Left $ JsonDecodeError x
98
rpcErrorJsonReport (J.Ok x) = return $ Right x
99

    
100
-- | Basic timeouts for RPC calls.
101
$(declareIADT "RpcTimeout"
102
  [ ( "Urgent",    'C.rpcTmoUrgent )
103
  , ( "Fast",      'C.rpcTmoFast )
104
  , ( "Normal",    'C.rpcTmoNormal )
105
  , ( "Slow",      'C.rpcTmoSlow )
106
  , ( "FourHours", 'C.rpcTmo4hrs )
107
  , ( "OneDay",    'C.rpcTmo1day )
108
  ])
109

    
110
-- | A generic class for RPC calls.
111
class (J.JSON a) => RpcCall a where
112
  -- | Give the (Python) name of the procedure.
113
  rpcCallName :: a -> String
114
  -- | Calculate the timeout value for the call execution.
115
  rpcCallTimeout :: a -> Int
116
  -- | Prepare arguments of the call to be send as POST.
117
  rpcCallData :: Node -> a -> String
118
  -- | Whether we accept offline nodes when making a call.
119
  rpcCallAcceptOffline :: a -> Bool
120

    
121
  rpcCallData _ = J.encode
122

    
123
-- | A generic class for RPC results with default implementation.
124
class (J.JSON a) => RpcResult a where
125
  -- | Create a result based on the received HTTP response.
126
  rpcResultFill :: (Monad m) => String -> m (Either RpcError a)
127

    
128
  rpcResultFill res = rpcErrorJsonReport $  J.decode res
129

    
130
-- | Generic class that ensures matching RPC call with its respective
131
-- result.
132
class (RpcCall a, RpcResult b) => Rpc a b | a -> b
133

    
134
-- | Http Request definition.
135
data HttpClientRequest = HttpClientRequest
136
  { requestTimeout :: Int
137
  , requestUrl :: String
138
  , requestPostData :: String
139
  }
140

    
141
-- | Execute the request and return the result as a plain String. When
142
-- curl reports an error, we propagate it.
143
executeHttpRequest :: Node -> Either RpcError HttpClientRequest
144
                   -> IO (Either RpcError String)
145

    
146
executeHttpRequest _ (Left rpc_err) = return $ Left rpc_err
147
#ifdef NO_CURL
148
executeHttpRequest _ _ = return $ Left CurlDisabledError
149
#else
150
executeHttpRequest node (Right request) = do
151
  let reqOpts = [ CurlTimeout (fromIntegral $ requestTimeout request)
152
                , CurlPostFields [requestPostData request]
153
                ]
154
      url = requestUrl request
155
  -- FIXME: This is very similar to getUrl in Htools/Rapi.hs
156
  (code, !body) <- curlGetString url $ curlOpts ++ reqOpts
157
  case code of
158
    CurlOK -> return $ Right body
159
    _ -> return $ Left $ CurlLayerError node (show code)
160
#endif
161

    
162
-- | Prepare url for the HTTP request.
163
prepareUrl :: (RpcCall a) => Node -> a -> String
164
prepareUrl node call =
165
  let node_ip = nodePrimaryIp node
166
      port = snd C.daemonsPortsGanetiNoded
167
      path_prefix = "https://" ++ (node_ip) ++ ":" ++ (show port) in
168
  path_prefix ++ "/" ++ rpcCallName call
169

    
170
-- | Create HTTP request for a given node provided it is online,
171
-- otherwise create empty response.
172
prepareHttpRequest ::  (RpcCall a) => Node -> a
173
                   -> Either RpcError HttpClientRequest
174
prepareHttpRequest node call
175
  | rpcCallAcceptOffline call ||
176
    (not $ nodeOffline node) =
177
      Right $ HttpClientRequest { requestTimeout = rpcCallTimeout call
178
                                , requestUrl = prepareUrl node call
179
                                , requestPostData = rpcCallData node call
180
                                }
181
  | otherwise = Left $ OfflineNodeError node
182

    
183
-- | Parse the response or propagate the error.
184
parseHttpResponse :: (Monad m, RpcResult a) => Either RpcError String
185
                  -> m (Either RpcError a)
186
parseHttpResponse (Left err) = return $ Left err
187
parseHttpResponse (Right response) = rpcResultFill response
188

    
189
-- | Execute RPC call for a sigle node.
190
executeSingleRpcCall :: (Rpc a b) => Node -> a -> IO (Node, Either RpcError b)
191
executeSingleRpcCall node call = do
192
  let request = prepareHttpRequest node call
193
  response <- executeHttpRequest node request
194
  result <- parseHttpResponse response
195
  return (node, result)
196

    
197
-- | Execute RPC call for many nodes in parallel.
198
executeRpcCall :: (Rpc a b) => [Node] -> a -> IO [(Node, Either RpcError b)]
199
executeRpcCall nodes call =
200
  sequence $ parMap rwhnf (uncurry executeSingleRpcCall)
201
               (zip nodes $ repeat call)
202

    
203
-- * RPC calls and results
204

    
205
-- | AllInstancesInfo
206
--   Returns information about all instances on the given nodes
207
$(buildObject "RpcCallAllInstancesInfo" "rpcCallAllInstInfo" $
208
  [ simpleField "hypervisors" [t| [Hypervisor] |] ])
209

    
210
$(buildObject "InstanceInfo" "instInfo" $
211
  [ simpleField "name"   [t| String |]
212
  , simpleField "memory" [t| Int|]
213
  , simpleField "state"  [t| AdminState |]
214
  , simpleField "vcpus"  [t| Int |]
215
  , simpleField "time"   [t| Int |]
216
  ])
217

    
218
$(buildObject "RpcResultAllInstancesInfo" "rpcResAllInstInfo" $
219
  [ simpleField "instances" [t| [InstanceInfo] |] ])
220

    
221
instance RpcCall RpcCallAllInstancesInfo where
222
  rpcCallName _ = "all_instances_info"
223
  rpcCallTimeout _ = rpcTimeoutToRaw Urgent
224
  rpcCallAcceptOffline _ = False
225

    
226
instance RpcResult RpcResultAllInstancesInfo
227

    
228
instance Rpc RpcCallAllInstancesInfo RpcResultAllInstancesInfo