Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / Luxi.hs @ 37904802

History | View | Annotate | Download (15.6 kB)

1 a0090487 Agata Murawska
{-# LANGUAGE TemplateHaskell #-}
2 a0090487 Agata Murawska
3 6583e677 Iustin Pop
{-| Implementation of the Ganeti LUXI interface.
4 6583e677 Iustin Pop
5 6583e677 Iustin Pop
-}
6 6583e677 Iustin Pop
7 6583e677 Iustin Pop
{-
8 6583e677 Iustin Pop
9 fae980e5 Iustin Pop
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
10 6583e677 Iustin Pop
11 6583e677 Iustin Pop
This program is free software; you can redistribute it and/or modify
12 6583e677 Iustin Pop
it under the terms of the GNU General Public License as published by
13 6583e677 Iustin Pop
the Free Software Foundation; either version 2 of the License, or
14 6583e677 Iustin Pop
(at your option) any later version.
15 6583e677 Iustin Pop
16 6583e677 Iustin Pop
This program is distributed in the hope that it will be useful, but
17 6583e677 Iustin Pop
WITHOUT ANY WARRANTY; without even the implied warranty of
18 6583e677 Iustin Pop
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 6583e677 Iustin Pop
General Public License for more details.
20 6583e677 Iustin Pop
21 6583e677 Iustin Pop
You should have received a copy of the GNU General Public License
22 6583e677 Iustin Pop
along with this program; if not, write to the Free Software
23 6583e677 Iustin Pop
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 6583e677 Iustin Pop
02110-1301, USA.
25 6583e677 Iustin Pop
26 6583e677 Iustin Pop
-}
27 6583e677 Iustin Pop
28 6583e677 Iustin Pop
module Ganeti.Luxi
29 ebf38064 Iustin Pop
  ( LuxiOp(..)
30 95d0d502 Iustin Pop
  , LuxiReq(..)
31 ebf38064 Iustin Pop
  , Client
32 ccc817a2 Iustin Pop
  , JobId
33 0aff2293 Iustin Pop
  , RecvResult(..)
34 0aff2293 Iustin Pop
  , strOfOp
35 ebf38064 Iustin Pop
  , getClient
36 13f2321c Iustin Pop
  , getServer
37 13f2321c Iustin Pop
  , acceptClient
38 ebf38064 Iustin Pop
  , closeClient
39 0aff2293 Iustin Pop
  , closeServer
40 ebf38064 Iustin Pop
  , callMethod
41 ebf38064 Iustin Pop
  , submitManyJobs
42 ebf38064 Iustin Pop
  , queryJobsStatus
43 cdd495ae Iustin Pop
  , buildCall
44 0aff2293 Iustin Pop
  , buildResponse
45 cdd495ae Iustin Pop
  , validateCall
46 cdd495ae Iustin Pop
  , decodeCall
47 13f2321c Iustin Pop
  , recvMsg
48 0aff2293 Iustin Pop
  , recvMsgExt
49 13f2321c Iustin Pop
  , sendMsg
50 471b6c46 Iustin Pop
  , allLuxiCalls
51 ebf38064 Iustin Pop
  ) where
52 6583e677 Iustin Pop
53 0aff2293 Iustin Pop
import Control.Exception (catch)
54 6583e677 Iustin Pop
import Data.IORef
55 76b62028 Iustin Pop
import Data.Ratio (numerator, denominator)
56 e821050d Iustin Pop
import qualified Data.ByteString as B
57 e821050d Iustin Pop
import qualified Data.ByteString.UTF8 as UTF8
58 e821050d Iustin Pop
import Data.Word (Word8)
59 6583e677 Iustin Pop
import Control.Monad
60 0903280b Iustin Pop
import Text.JSON (encodeStrict, decodeStrict)
61 6583e677 Iustin Pop
import qualified Text.JSON as J
62 7adb7dff Iustin Pop
import Text.JSON.Pretty (pp_value)
63 6583e677 Iustin Pop
import Text.JSON.Types
64 0aff2293 Iustin Pop
import System.Directory (removeFile)
65 e821050d Iustin Pop
import System.IO (hClose, hFlush, hWaitForInput, Handle, IOMode(..))
66 0aff2293 Iustin Pop
import System.IO.Error (isEOFError)
67 6583e677 Iustin Pop
import System.Timeout
68 6583e677 Iustin Pop
import qualified Network.Socket as S
69 6583e677 Iustin Pop
70 4cd79ca8 Iustin Pop
import Ganeti.BasicTypes
71 92678b3c Iustin Pop
import Ganeti.Constants
72 7adb7dff Iustin Pop
import Ganeti.Errors
73 7adb7dff Iustin Pop
import Ganeti.JSON
74 9a2ff880 Iustin Pop
import Ganeti.Jobs (JobStatus)
75 367c4241 Dato Simó
import Ganeti.OpCodes
76 7adb7dff Iustin Pop
import Ganeti.Utils
77 4cab6703 Iustin Pop
import qualified Ganeti.Query.Language as Qlang
78 a0090487 Agata Murawska
import Ganeti.THH
79 9a2ff880 Iustin Pop
80 6583e677 Iustin Pop
-- * Utility functions
81 6583e677 Iustin Pop
82 6583e677 Iustin Pop
-- | Wrapper over System.Timeout.timeout that fails in the IO monad.
83 6583e677 Iustin Pop
withTimeout :: Int -> String -> IO a -> IO a
84 6583e677 Iustin Pop
withTimeout secs descr action = do
85 ebf38064 Iustin Pop
  result <- timeout (secs * 1000000) action
86 3603605a Iustin Pop
  case result of
87 3603605a Iustin Pop
    Nothing -> fail $ "Timeout in " ++ descr
88 3603605a Iustin Pop
    Just v -> return v
89 6583e677 Iustin Pop
90 6583e677 Iustin Pop
-- * Generic protocol functionality
91 6583e677 Iustin Pop
92 0aff2293 Iustin Pop
-- | Result of receiving a message from the socket.
93 0aff2293 Iustin Pop
data RecvResult = RecvConnClosed    -- ^ Connection closed
94 0aff2293 Iustin Pop
                | RecvError String  -- ^ Any other error
95 0aff2293 Iustin Pop
                | RecvOk String     -- ^ Successfull receive
96 0aff2293 Iustin Pop
                  deriving (Show, Read, Eq)
97 0aff2293 Iustin Pop
98 ccc817a2 Iustin Pop
-- | The Ganeti job type.
99 76b62028 Iustin Pop
type JobId = Int
100 ccc817a2 Iustin Pop
101 a0090487 Agata Murawska
-- | Currently supported Luxi operations and JSON serialization.
102 a0090487 Agata Murawska
$(genLuxiOp "LuxiOp"
103 72295708 Iustin Pop
  [ (luxiReqQuery,
104 88609f00 Iustin Pop
    [ simpleField "what"    [t| Qlang.ItemType |]
105 88609f00 Iustin Pop
    , simpleField "fields"  [t| [String]  |]
106 88609f00 Iustin Pop
    , simpleField "qfilter" [t| Qlang.Filter Qlang.FilterField |]
107 ebf38064 Iustin Pop
    ])
108 72295708 Iustin Pop
  , (luxiReqQueryFields,
109 88609f00 Iustin Pop
    [ simpleField "what"    [t| Qlang.ItemType |]
110 88609f00 Iustin Pop
    , simpleField "fields"  [t| [String]  |]
111 72295708 Iustin Pop
    ])
112 fae980e5 Iustin Pop
  , (luxiReqQueryNodes,
113 88609f00 Iustin Pop
     [ simpleField "names"  [t| [String] |]
114 88609f00 Iustin Pop
     , simpleField "fields" [t| [String] |]
115 88609f00 Iustin Pop
     , simpleField "lock"   [t| Bool     |]
116 ebf38064 Iustin Pop
     ])
117 fae980e5 Iustin Pop
  , (luxiReqQueryGroups,
118 88609f00 Iustin Pop
     [ simpleField "names"  [t| [String] |]
119 88609f00 Iustin Pop
     , simpleField "fields" [t| [String] |]
120 88609f00 Iustin Pop
     , simpleField "lock"   [t| Bool     |]
121 ebf38064 Iustin Pop
     ])
122 fae980e5 Iustin Pop
  , (luxiReqQueryInstances,
123 88609f00 Iustin Pop
     [ simpleField "names"  [t| [String] |]
124 88609f00 Iustin Pop
     , simpleField "fields" [t| [String] |]
125 88609f00 Iustin Pop
     , simpleField "lock"   [t| Bool     |]
126 ebf38064 Iustin Pop
     ])
127 fae980e5 Iustin Pop
  , (luxiReqQueryJobs,
128 88609f00 Iustin Pop
     [ simpleField "ids"    [t| [Int]    |]
129 88609f00 Iustin Pop
     , simpleField "fields" [t| [String] |]
130 ebf38064 Iustin Pop
     ])
131 fae980e5 Iustin Pop
  , (luxiReqQueryExports,
132 88609f00 Iustin Pop
     [ simpleField "nodes" [t| [String] |]
133 88609f00 Iustin Pop
     , simpleField "lock"  [t| Bool     |]
134 ebf38064 Iustin Pop
     ])
135 fae980e5 Iustin Pop
  , (luxiReqQueryConfigValues,
136 88609f00 Iustin Pop
     [ simpleField "fields" [t| [String] |] ]
137 ebf38064 Iustin Pop
    )
138 fae980e5 Iustin Pop
  , (luxiReqQueryClusterInfo, [])
139 fae980e5 Iustin Pop
  , (luxiReqQueryTags,
140 d8e7c45e Iustin Pop
     [ customField 'decodeTagObject 'encodeTagObject $
141 d8e7c45e Iustin Pop
       simpleField "kind" [t| TagObject |]
142 ebf38064 Iustin Pop
     ])
143 fae980e5 Iustin Pop
  , (luxiReqSubmitJob,
144 88609f00 Iustin Pop
     [ simpleField "job" [t| [OpCode] |] ]
145 ebf38064 Iustin Pop
    )
146 fae980e5 Iustin Pop
  , (luxiReqSubmitManyJobs,
147 88609f00 Iustin Pop
     [ simpleField "ops" [t| [[OpCode]] |] ]
148 ebf38064 Iustin Pop
    )
149 fae980e5 Iustin Pop
  , (luxiReqWaitForJobChange,
150 88609f00 Iustin Pop
     [ simpleField "job"      [t| Int     |]
151 88609f00 Iustin Pop
     , simpleField "fields"   [t| [String]|]
152 88609f00 Iustin Pop
     , simpleField "prev_job" [t| JSValue |]
153 88609f00 Iustin Pop
     , simpleField "prev_log" [t| JSValue |]
154 88609f00 Iustin Pop
     , simpleField "tmout"    [t| Int     |]
155 ebf38064 Iustin Pop
     ])
156 fae980e5 Iustin Pop
  , (luxiReqArchiveJob,
157 88609f00 Iustin Pop
     [ simpleField "job" [t| Int |] ]
158 ebf38064 Iustin Pop
    )
159 fae980e5 Iustin Pop
  , (luxiReqAutoArchiveJobs,
160 88609f00 Iustin Pop
     [ simpleField "age"   [t| Int |]
161 88609f00 Iustin Pop
     , simpleField "tmout" [t| Int |]
162 ebf38064 Iustin Pop
     ])
163 fae980e5 Iustin Pop
  , (luxiReqCancelJob,
164 88609f00 Iustin Pop
     [ simpleField "job" [t| Int |] ]
165 ebf38064 Iustin Pop
    )
166 fae980e5 Iustin Pop
  , (luxiReqSetDrainFlag,
167 88609f00 Iustin Pop
     [ simpleField "flag" [t| Bool |] ]
168 ebf38064 Iustin Pop
    )
169 fae980e5 Iustin Pop
  , (luxiReqSetWatcherPause,
170 88609f00 Iustin Pop
     [ simpleField "duration" [t| Double |] ]
171 ebf38064 Iustin Pop
    )
172 a0090487 Agata Murawska
  ])
173 6583e677 Iustin Pop
174 95d0d502 Iustin Pop
$(makeJSONInstance ''LuxiReq)
175 95d0d502 Iustin Pop
176 471b6c46 Iustin Pop
-- | List of all defined Luxi calls.
177 471b6c46 Iustin Pop
$(genAllConstr (drop 3) ''LuxiReq "allLuxiCalls")
178 471b6c46 Iustin Pop
179 6583e677 Iustin Pop
-- | The serialisation of LuxiOps into strings in messages.
180 a0090487 Agata Murawska
$(genStrOfOp ''LuxiOp "strOfOp")
181 6583e677 Iustin Pop
182 cdd495ae Iustin Pop
-- | Type holding the initial (unparsed) Luxi call.
183 cdd495ae Iustin Pop
data LuxiCall = LuxiCall LuxiReq JSValue
184 cdd495ae Iustin Pop
185 6583e677 Iustin Pop
-- | The end-of-message separator.
186 e821050d Iustin Pop
eOM :: Word8
187 e821050d Iustin Pop
eOM = 3
188 e821050d Iustin Pop
189 e821050d Iustin Pop
-- | The end-of-message encoded as a ByteString.
190 e821050d Iustin Pop
bEOM :: B.ByteString
191 e821050d Iustin Pop
bEOM = B.singleton eOM
192 6583e677 Iustin Pop
193 6583e677 Iustin Pop
-- | Valid keys in the requests and responses.
194 6583e677 Iustin Pop
data MsgKeys = Method
195 6583e677 Iustin Pop
             | Args
196 6583e677 Iustin Pop
             | Success
197 6583e677 Iustin Pop
             | Result
198 6583e677 Iustin Pop
199 6583e677 Iustin Pop
-- | The serialisation of MsgKeys into strings in messages.
200 a0090487 Agata Murawska
$(genStrOfKey ''MsgKeys "strOfKey")
201 6583e677 Iustin Pop
202 6583e677 Iustin Pop
-- | Luxi client encapsulation.
203 e821050d Iustin Pop
data Client = Client { socket :: Handle           -- ^ The socket of the client
204 e821050d Iustin Pop
                     , rbuf :: IORef B.ByteString -- ^ Already received buffer
205 6583e677 Iustin Pop
                     }
206 6583e677 Iustin Pop
207 6583e677 Iustin Pop
-- | Connects to the master daemon and returns a luxi Client.
208 6583e677 Iustin Pop
getClient :: String -> IO Client
209 6583e677 Iustin Pop
getClient path = do
210 ebf38064 Iustin Pop
  s <- S.socket S.AF_UNIX S.Stream S.defaultProtocol
211 4cd79ca8 Iustin Pop
  withTimeout luxiDefCtmo "creating luxi connection" $
212 ebf38064 Iustin Pop
              S.connect s (S.SockAddrUnix path)
213 e821050d Iustin Pop
  rf <- newIORef B.empty
214 e821050d Iustin Pop
  h <- S.socketToHandle s ReadWriteMode
215 e821050d Iustin Pop
  return Client { socket=h, rbuf=rf }
216 6583e677 Iustin Pop
217 13f2321c Iustin Pop
-- | Creates and returns a server endpoint.
218 13f2321c Iustin Pop
getServer :: FilePath -> IO S.Socket
219 13f2321c Iustin Pop
getServer path = do
220 13f2321c Iustin Pop
  s <- S.socket S.AF_UNIX S.Stream S.defaultProtocol
221 13f2321c Iustin Pop
  S.bindSocket s (S.SockAddrUnix path)
222 13f2321c Iustin Pop
  S.listen s 5 -- 5 is the max backlog
223 13f2321c Iustin Pop
  return s
224 13f2321c Iustin Pop
225 0aff2293 Iustin Pop
-- | Closes a server endpoint.
226 0aff2293 Iustin Pop
-- FIXME: this should be encapsulated into a nicer type.
227 0aff2293 Iustin Pop
closeServer :: FilePath -> S.Socket -> IO ()
228 0aff2293 Iustin Pop
closeServer path sock = do
229 0aff2293 Iustin Pop
  S.sClose sock
230 0aff2293 Iustin Pop
  removeFile path
231 0aff2293 Iustin Pop
232 13f2321c Iustin Pop
-- | Accepts a client
233 13f2321c Iustin Pop
acceptClient :: S.Socket -> IO Client
234 13f2321c Iustin Pop
acceptClient s = do
235 13f2321c Iustin Pop
  -- second return is the address of the client, which we ignore here
236 13f2321c Iustin Pop
  (client_socket, _) <- S.accept s
237 13f2321c Iustin Pop
  new_buffer <- newIORef B.empty
238 13f2321c Iustin Pop
  handle <- S.socketToHandle client_socket ReadWriteMode
239 13f2321c Iustin Pop
  return Client { socket=handle, rbuf=new_buffer }
240 13f2321c Iustin Pop
241 6583e677 Iustin Pop
-- | Closes the client socket.
242 6583e677 Iustin Pop
closeClient :: Client -> IO ()
243 e821050d Iustin Pop
closeClient = hClose . socket
244 6583e677 Iustin Pop
245 6583e677 Iustin Pop
-- | Sends a message over a luxi transport.
246 6583e677 Iustin Pop
sendMsg :: Client -> String -> IO ()
247 4cd79ca8 Iustin Pop
sendMsg s buf = withTimeout luxiDefRwto "sending luxi message" $ do
248 e821050d Iustin Pop
  let encoded = UTF8.fromString buf
249 e821050d Iustin Pop
      handle = socket s
250 e821050d Iustin Pop
  B.hPut handle encoded
251 e821050d Iustin Pop
  B.hPut handle bEOM
252 e821050d Iustin Pop
  hFlush handle
253 e821050d Iustin Pop
254 e821050d Iustin Pop
-- | Given a current buffer and the handle, it will read from the
255 e821050d Iustin Pop
-- network until we get a full message, and it will return that
256 e821050d Iustin Pop
-- message and the leftover buffer contents.
257 e821050d Iustin Pop
recvUpdate :: Handle -> B.ByteString -> IO (B.ByteString, B.ByteString)
258 e821050d Iustin Pop
recvUpdate handle obuf = do
259 4cd79ca8 Iustin Pop
  nbuf <- withTimeout luxiDefRwto "reading luxi response" $ do
260 e821050d Iustin Pop
            _ <- hWaitForInput handle (-1)
261 e821050d Iustin Pop
            B.hGetNonBlocking handle 4096
262 e821050d Iustin Pop
  let (msg, remaining) = B.break (eOM ==) nbuf
263 e821050d Iustin Pop
      newbuf = B.append obuf msg
264 e821050d Iustin Pop
  if B.null remaining
265 e821050d Iustin Pop
    then recvUpdate handle newbuf
266 e821050d Iustin Pop
    else return (newbuf, B.tail remaining)
267 6583e677 Iustin Pop
268 6583e677 Iustin Pop
-- | Waits for a message over a luxi transport.
269 6583e677 Iustin Pop
recvMsg :: Client -> IO String
270 6583e677 Iustin Pop
recvMsg s = do
271 6583e677 Iustin Pop
  cbuf <- readIORef $ rbuf s
272 e821050d Iustin Pop
  let (imsg, ibuf) = B.break (eOM ==) cbuf
273 95f490de Iustin Pop
  (msg, nbuf) <-
274 e821050d Iustin Pop
    if B.null ibuf      -- if old buffer didn't contain a full message
275 e821050d Iustin Pop
      then recvUpdate (socket s) cbuf   -- then we read from network
276 e821050d Iustin Pop
      else return (imsg, B.tail ibuf)   -- else we return data from our buffer
277 6583e677 Iustin Pop
  writeIORef (rbuf s) nbuf
278 e821050d Iustin Pop
  return $ UTF8.toString msg
279 6583e677 Iustin Pop
280 0aff2293 Iustin Pop
-- | Extended wrapper over recvMsg.
281 0aff2293 Iustin Pop
recvMsgExt :: Client -> IO RecvResult
282 0aff2293 Iustin Pop
recvMsgExt s =
283 7ae5d703 Iustin Pop
  Control.Exception.catch (liftM RecvOk (recvMsg s)) $ \e ->
284 66ad857a Iustin Pop
    return $ if isEOFError e
285 66ad857a Iustin Pop
               then RecvConnClosed
286 66ad857a Iustin Pop
               else RecvError (show e)
287 0aff2293 Iustin Pop
288 6583e677 Iustin Pop
-- | Serialize a request to String.
289 6583e677 Iustin Pop
buildCall :: LuxiOp  -- ^ The method
290 6583e677 Iustin Pop
          -> String  -- ^ The serialized form
291 683b1ca7 Iustin Pop
buildCall lo =
292 2cdaf225 Iustin Pop
  let ja = [ (strOfKey Method, J.showJSON $ strOfOp lo)
293 2cdaf225 Iustin Pop
           , (strOfKey Args, opToArgs lo)
294 ebf38064 Iustin Pop
           ]
295 ebf38064 Iustin Pop
      jo = toJSObject ja
296 ebf38064 Iustin Pop
  in encodeStrict jo
297 6583e677 Iustin Pop
298 0aff2293 Iustin Pop
-- | Serialize the response to String.
299 0aff2293 Iustin Pop
buildResponse :: Bool    -- ^ Success
300 0aff2293 Iustin Pop
              -> JSValue -- ^ The arguments
301 0aff2293 Iustin Pop
              -> String  -- ^ The serialized form
302 0aff2293 Iustin Pop
buildResponse success args =
303 0aff2293 Iustin Pop
  let ja = [ (strOfKey Success, JSBool success)
304 0aff2293 Iustin Pop
           , (strOfKey Result, args)]
305 0aff2293 Iustin Pop
      jo = toJSObject ja
306 0aff2293 Iustin Pop
  in encodeStrict jo
307 0aff2293 Iustin Pop
308 cdd495ae Iustin Pop
-- | Check that luxi request contains the required keys and parse it.
309 cdd495ae Iustin Pop
validateCall :: String -> Result LuxiCall
310 cdd495ae Iustin Pop
validateCall s = do
311 0aff2293 Iustin Pop
  arr <- fromJResult "parsing top-level luxi message" $
312 0aff2293 Iustin Pop
         decodeStrict s::Result (JSObject JSValue)
313 cdd495ae Iustin Pop
  let aobj = fromJSObject arr
314 cdd495ae Iustin Pop
  call <- fromObj aobj (strOfKey Method)::Result LuxiReq
315 cdd495ae Iustin Pop
  args <- fromObj aobj (strOfKey Args)
316 cdd495ae Iustin Pop
  return (LuxiCall call args)
317 cdd495ae Iustin Pop
318 cdd495ae Iustin Pop
-- | Converts Luxi call arguments into a 'LuxiOp' data structure.
319 cdd495ae Iustin Pop
--
320 cdd495ae Iustin Pop
-- This is currently hand-coded until we make it more uniform so that
321 cdd495ae Iustin Pop
-- it can be generated using TH.
322 cdd495ae Iustin Pop
decodeCall :: LuxiCall -> Result LuxiOp
323 cdd495ae Iustin Pop
decodeCall (LuxiCall call args) =
324 cdd495ae Iustin Pop
  case call of
325 cdd495ae Iustin Pop
    ReqQueryJobs -> do
326 cdd495ae Iustin Pop
              (jid, jargs) <- fromJVal args
327 76b62028 Iustin Pop
              rid <- mapM parseJobId jid
328 cdd495ae Iustin Pop
              let rargs = map fromJSString jargs
329 cdd495ae Iustin Pop
              return $ QueryJobs rid rargs
330 cdd495ae Iustin Pop
    ReqQueryInstances -> do
331 cdd495ae Iustin Pop
              (names, fields, locking) <- fromJVal args
332 cdd495ae Iustin Pop
              return $ QueryInstances names fields locking
333 cdd495ae Iustin Pop
    ReqQueryNodes -> do
334 cdd495ae Iustin Pop
              (names, fields, locking) <- fromJVal args
335 cdd495ae Iustin Pop
              return $ QueryNodes names fields locking
336 cdd495ae Iustin Pop
    ReqQueryGroups -> do
337 cdd495ae Iustin Pop
              (names, fields, locking) <- fromJVal args
338 cdd495ae Iustin Pop
              return $ QueryGroups names fields locking
339 5b11f8db Iustin Pop
    ReqQueryClusterInfo ->
340 cdd495ae Iustin Pop
              return QueryClusterInfo
341 cdd495ae Iustin Pop
    ReqQuery -> do
342 9a94c848 Iustin Pop
              (what, fields, qfilter) <- fromJVal args
343 9a94c848 Iustin Pop
              return $ Query what fields qfilter
344 72295708 Iustin Pop
    ReqQueryFields -> do
345 72295708 Iustin Pop
              (what, fields) <- fromJVal args
346 72295708 Iustin Pop
              fields' <- case fields of
347 72295708 Iustin Pop
                           JSNull -> return []
348 72295708 Iustin Pop
                           _ -> fromJVal fields
349 72295708 Iustin Pop
              return $ QueryFields what fields'
350 cdd495ae Iustin Pop
    ReqSubmitJob -> do
351 cdd495ae Iustin Pop
              [ops1] <- fromJVal args
352 cdd495ae Iustin Pop
              ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1
353 cdd495ae Iustin Pop
              return $ SubmitJob ops2
354 cdd495ae Iustin Pop
    ReqSubmitManyJobs -> do
355 cdd495ae Iustin Pop
              [ops1] <- fromJVal args
356 cdd495ae Iustin Pop
              ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1
357 cdd495ae Iustin Pop
              return $ SubmitManyJobs ops2
358 cdd495ae Iustin Pop
    ReqWaitForJobChange -> do
359 cdd495ae Iustin Pop
              (jid, fields, pinfo, pidx, wtmout) <-
360 cdd495ae Iustin Pop
                -- No instance for 5-tuple, code copied from the
361 cdd495ae Iustin Pop
                -- json sources and adapted
362 cdd495ae Iustin Pop
                fromJResult "Parsing WaitForJobChange message" $
363 cdd495ae Iustin Pop
                case args of
364 cdd495ae Iustin Pop
                  JSArray [a, b, c, d, e] ->
365 cdd495ae Iustin Pop
                    (,,,,) `fmap`
366 cdd495ae Iustin Pop
                    J.readJSON a `ap`
367 cdd495ae Iustin Pop
                    J.readJSON b `ap`
368 cdd495ae Iustin Pop
                    J.readJSON c `ap`
369 cdd495ae Iustin Pop
                    J.readJSON d `ap`
370 cdd495ae Iustin Pop
                    J.readJSON e
371 cdd495ae Iustin Pop
                  _ -> J.Error "Not enough values"
372 76b62028 Iustin Pop
              rid <- parseJobId jid
373 cdd495ae Iustin Pop
              return $ WaitForJobChange rid fields pinfo pidx wtmout
374 cdd495ae Iustin Pop
    ReqArchiveJob -> do
375 cdd495ae Iustin Pop
              [jid] <- fromJVal args
376 76b62028 Iustin Pop
              rid <- parseJobId jid
377 cdd495ae Iustin Pop
              return $ ArchiveJob rid
378 cdd495ae Iustin Pop
    ReqAutoArchiveJobs -> do
379 cdd495ae Iustin Pop
              (age, tmout) <- fromJVal args
380 cdd495ae Iustin Pop
              return $ AutoArchiveJobs age tmout
381 cdd495ae Iustin Pop
    ReqQueryExports -> do
382 cdd495ae Iustin Pop
              (nodes, lock) <- fromJVal args
383 cdd495ae Iustin Pop
              return $ QueryExports nodes lock
384 cdd495ae Iustin Pop
    ReqQueryConfigValues -> do
385 cdd495ae Iustin Pop
              [fields] <- fromJVal args
386 cdd495ae Iustin Pop
              return $ QueryConfigValues fields
387 cdd495ae Iustin Pop
    ReqQueryTags -> do
388 cdd495ae Iustin Pop
              (kind, name) <- fromJVal args
389 d8e7c45e Iustin Pop
              item <- tagObjectFrom kind name
390 d8e7c45e Iustin Pop
              return $ QueryTags item
391 cdd495ae Iustin Pop
    ReqCancelJob -> do
392 cdd495ae Iustin Pop
              [job] <- fromJVal args
393 76b62028 Iustin Pop
              rid <- parseJobId job
394 cdd495ae Iustin Pop
              return $ CancelJob rid
395 cdd495ae Iustin Pop
    ReqSetDrainFlag -> do
396 cdd495ae Iustin Pop
              [flag] <- fromJVal args
397 cdd495ae Iustin Pop
              return $ SetDrainFlag flag
398 cdd495ae Iustin Pop
    ReqSetWatcherPause -> do
399 cdd495ae Iustin Pop
              [duration] <- fromJVal args
400 cdd495ae Iustin Pop
              return $ SetWatcherPause duration
401 cdd495ae Iustin Pop
402 6583e677 Iustin Pop
-- | Check that luxi responses contain the required keys and that the
403 6583e677 Iustin Pop
-- call was successful.
404 7adb7dff Iustin Pop
validateResult :: String -> ErrorResult JSValue
405 6583e677 Iustin Pop
validateResult s = do
406 e821050d Iustin Pop
  when (UTF8.replacement_char `elem` s) $
407 e821050d Iustin Pop
       fail "Failed to decode UTF-8, detected replacement char after decoding"
408 7adb7dff Iustin Pop
  oarr <- fromJResult "Parsing LUXI response" (decodeStrict s)
409 262f3e6c Iustin Pop
  let arr = J.fromJSObject oarr
410 7adb7dff Iustin Pop
  status <- fromObj arr (strOfKey Success)
411 7adb7dff Iustin Pop
  result <- fromObj arr (strOfKey Result)
412 3603605a Iustin Pop
  if status
413 7adb7dff Iustin Pop
    then return result
414 7adb7dff Iustin Pop
    else decodeError result
415 7adb7dff Iustin Pop
416 7adb7dff Iustin Pop
-- | Try to decode an error from the server response. This function
417 7adb7dff Iustin Pop
-- will always fail, since it's called only on the error path (when
418 7adb7dff Iustin Pop
-- status is False).
419 7adb7dff Iustin Pop
decodeError :: JSValue -> ErrorResult JSValue
420 7adb7dff Iustin Pop
decodeError val =
421 7adb7dff Iustin Pop
  case fromJVal val of
422 7adb7dff Iustin Pop
    Ok e -> Bad e
423 7adb7dff Iustin Pop
    Bad msg -> Bad $ GenericError msg
424 6583e677 Iustin Pop
425 6583e677 Iustin Pop
-- | Generic luxi method call.
426 7adb7dff Iustin Pop
callMethod :: LuxiOp -> Client -> IO (ErrorResult JSValue)
427 683b1ca7 Iustin Pop
callMethod method s = do
428 683b1ca7 Iustin Pop
  sendMsg s $ buildCall method
429 6583e677 Iustin Pop
  result <- recvMsg s
430 6583e677 Iustin Pop
  let rval = validateResult result
431 6583e677 Iustin Pop
  return rval
432 9a2ff880 Iustin Pop
433 619e89c8 Iustin Pop
-- | Parses a job ID.
434 619e89c8 Iustin Pop
parseJobId :: JSValue -> Result JobId
435 76b62028 Iustin Pop
parseJobId (JSString x) = tryRead "parsing job id" . fromJSString $ x
436 76b62028 Iustin Pop
parseJobId (JSRational _ x) =
437 76b62028 Iustin Pop
  if denominator x /= 1
438 76b62028 Iustin Pop
    then Bad $ "Got fractional job ID from master daemon?! Value:" ++ show x
439 76b62028 Iustin Pop
    -- FIXME: potential integer overflow here on 32-bit platforms
440 76b62028 Iustin Pop
    else Ok . fromIntegral . numerator $ x
441 619e89c8 Iustin Pop
parseJobId x = Bad $ "Wrong type/value for job id: " ++ show x
442 619e89c8 Iustin Pop
443 619e89c8 Iustin Pop
-- | Parse job submission result.
444 7adb7dff Iustin Pop
parseSubmitJobResult :: JSValue -> ErrorResult JobId
445 7adb7dff Iustin Pop
parseSubmitJobResult (JSArray [JSBool True, v]) =
446 7adb7dff Iustin Pop
  case parseJobId v of
447 7adb7dff Iustin Pop
    Bad msg -> Bad $ LuxiError msg
448 7adb7dff Iustin Pop
    Ok v' -> Ok v'
449 619e89c8 Iustin Pop
parseSubmitJobResult (JSArray [JSBool False, JSString x]) =
450 7adb7dff Iustin Pop
  Bad . LuxiError $ fromJSString x
451 7adb7dff Iustin Pop
parseSubmitJobResult v =
452 7adb7dff Iustin Pop
  Bad . LuxiError $ "Unknown result from the master daemon: " ++
453 7adb7dff Iustin Pop
      show (pp_value v)
454 619e89c8 Iustin Pop
455 9a2ff880 Iustin Pop
-- | Specialized submitManyJobs call.
456 7adb7dff Iustin Pop
submitManyJobs :: Client -> [[OpCode]] -> IO (ErrorResult [JobId])
457 9a2ff880 Iustin Pop
submitManyJobs s jobs = do
458 683b1ca7 Iustin Pop
  rval <- callMethod (SubmitManyJobs jobs) s
459 9a2ff880 Iustin Pop
  -- map each result (status, payload) pair into a nice Result ADT
460 9a2ff880 Iustin Pop
  return $ case rval of
461 9a2ff880 Iustin Pop
             Bad x -> Bad x
462 619e89c8 Iustin Pop
             Ok (JSArray r) -> mapM parseSubmitJobResult r
463 7adb7dff Iustin Pop
             x -> Bad . LuxiError $
464 7adb7dff Iustin Pop
                  "Cannot parse response from Ganeti: " ++ show x
465 9a2ff880 Iustin Pop
466 9a2ff880 Iustin Pop
-- | Custom queryJobs call.
467 7adb7dff Iustin Pop
queryJobsStatus :: Client -> [JobId] -> IO (ErrorResult [JobStatus])
468 9a2ff880 Iustin Pop
queryJobsStatus s jids = do
469 76b62028 Iustin Pop
  rval <- callMethod (QueryJobs jids ["status"]) s
470 9a2ff880 Iustin Pop
  return $ case rval of
471 9a2ff880 Iustin Pop
             Bad x -> Bad x
472 9a2ff880 Iustin Pop
             Ok y -> case J.readJSON y::(J.Result [[JobStatus]]) of
473 9a2ff880 Iustin Pop
                       J.Ok vals -> if any null vals
474 7adb7dff Iustin Pop
                                    then Bad $
475 7adb7dff Iustin Pop
                                         LuxiError "Missing job status field"
476 9a2ff880 Iustin Pop
                                    else Ok (map head vals)
477 7adb7dff Iustin Pop
                       J.Error x -> Bad $ LuxiError x