Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / Query / Server.hs @ 9d0b521e

History | View | Annotate | Download (10.4 kB)

1 25b54de0 Iustin Pop
{-# LANGUAGE BangPatterns #-}
2 25b54de0 Iustin Pop
3 d120506c Agata Murawska
{-| Implementation of the Ganeti Query2 server.
4 25b54de0 Iustin Pop
5 25b54de0 Iustin Pop
-}
6 25b54de0 Iustin Pop
7 25b54de0 Iustin Pop
{-
8 25b54de0 Iustin Pop
9 72747d91 Iustin Pop
Copyright (C) 2012, 2013 Google Inc.
10 25b54de0 Iustin Pop
11 25b54de0 Iustin Pop
This program is free software; you can redistribute it and/or modify
12 25b54de0 Iustin Pop
it under the terms of the GNU General Public License as published by
13 25b54de0 Iustin Pop
the Free Software Foundation; either version 2 of the License, or
14 25b54de0 Iustin Pop
(at your option) any later version.
15 25b54de0 Iustin Pop
16 25b54de0 Iustin Pop
This program is distributed in the hope that it will be useful, but
17 25b54de0 Iustin Pop
WITHOUT ANY WARRANTY; without even the implied warranty of
18 25b54de0 Iustin Pop
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 25b54de0 Iustin Pop
General Public License for more details.
20 25b54de0 Iustin Pop
21 25b54de0 Iustin Pop
You should have received a copy of the GNU General Public License
22 25b54de0 Iustin Pop
along with this program; if not, write to the Free Software
23 25b54de0 Iustin Pop
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 25b54de0 Iustin Pop
02110-1301, USA.
25 25b54de0 Iustin Pop
26 25b54de0 Iustin Pop
-}
27 25b54de0 Iustin Pop
28 4cab6703 Iustin Pop
module Ganeti.Query.Server
29 670e954a Thomas Thrainer
  ( main
30 670e954a Thomas Thrainer
  , checkMain
31 670e954a Thomas Thrainer
  , prepMain
32 0d0ac025 Iustin Pop
  ) where
33 25b54de0 Iustin Pop
34 f2374060 Iustin Pop
import Control.Applicative
35 25b54de0 Iustin Pop
import Control.Concurrent
36 25b54de0 Iustin Pop
import Control.Exception
37 670e954a Thomas Thrainer
import Control.Monad (forever)
38 25b54de0 Iustin Pop
import Data.Bits (bitSize)
39 670e954a Thomas Thrainer
import Data.IORef
40 25b54de0 Iustin Pop
import qualified Network.Socket as S
41 25b54de0 Iustin Pop
import qualified Text.JSON as J
42 25b54de0 Iustin Pop
import Text.JSON (showJSON, JSValue(..))
43 25b54de0 Iustin Pop
import System.Info (arch)
44 25b54de0 Iustin Pop
45 25b54de0 Iustin Pop
import qualified Ganeti.Constants as C
46 5183e8be Iustin Pop
import Ganeti.Errors
47 9eeb0aa5 Michael Hanselmann
import qualified Ganeti.Path as Path
48 0d0ac025 Iustin Pop
import Ganeti.Daemon
49 25b54de0 Iustin Pop
import Ganeti.Objects
50 f2374060 Iustin Pop
import qualified Ganeti.Config as Config
51 218e3b0f Thomas Thrainer
import Ganeti.ConfigReader
52 25b54de0 Iustin Pop
import Ganeti.BasicTypes
53 25b54de0 Iustin Pop
import Ganeti.Logging
54 25b54de0 Iustin Pop
import Ganeti.Luxi
55 367c4241 Dato Simó
import Ganeti.OpCodes (TagObject(..))
56 4cab6703 Iustin Pop
import qualified Ganeti.Query.Language as Qlang
57 4cbe9bda Iustin Pop
import Ganeti.Query.Query
58 c4e0d065 Klaus Aehlig
import Ganeti.Query.Filter (makeSimpleFilter)
59 25b54de0 Iustin Pop
60 cd67e337 Iustin Pop
-- | Helper for classic queries.
61 cd67e337 Iustin Pop
handleClassicQuery :: ConfigData      -- ^ Cluster config
62 cd67e337 Iustin Pop
                   -> Qlang.ItemType  -- ^ Query type
63 037762a9 Iustin Pop
                   -> [Either String Integer] -- ^ Requested names
64 037762a9 Iustin Pop
                                              -- (empty means all)
65 cd67e337 Iustin Pop
                   -> [String]        -- ^ Requested fields
66 cd67e337 Iustin Pop
                   -> Bool            -- ^ Whether to do sync queries or not
67 5183e8be Iustin Pop
                   -> IO (GenericResult GanetiException JSValue)
68 c4e0d065 Klaus Aehlig
handleClassicQuery _ _ _ _ True =
69 5183e8be Iustin Pop
  return . Bad $ OpPrereqError "Sync queries are not allowed" ECodeInval
70 c4e0d065 Klaus Aehlig
handleClassicQuery cfg qkind names fields _ = do
71 c4e0d065 Klaus Aehlig
  let flt = makeSimpleFilter (nameField qkind) names
72 cd67e337 Iustin Pop
  qr <- query cfg True (Qlang.Query qkind fields flt)
73 cd67e337 Iustin Pop
  return $ showJSON <$> (qr >>= queryCompat)
74 cd67e337 Iustin Pop
75 25b54de0 Iustin Pop
-- | Minimal wrapper to handle the missing config case.
76 5183e8be Iustin Pop
handleCallWrapper :: Result ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
77 25b54de0 Iustin Pop
handleCallWrapper (Bad msg) _ =
78 5183e8be Iustin Pop
  return . Bad . ConfigurationError $
79 5183e8be Iustin Pop
           "I do not have access to a valid configuration, cannot\
80 5183e8be Iustin Pop
           \ process queries: " ++ msg
81 25b54de0 Iustin Pop
handleCallWrapper (Ok config) op = handleCall config op
82 25b54de0 Iustin Pop
83 25b54de0 Iustin Pop
-- | Actual luxi operation handler.
84 5183e8be Iustin Pop
handleCall :: ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
85 25b54de0 Iustin Pop
handleCall cdata QueryClusterInfo =
86 25b54de0 Iustin Pop
  let cluster = configCluster cdata
87 25b54de0 Iustin Pop
      hypervisors = clusterEnabledHypervisors cluster
88 966e1580 Helga Velroyen
      diskTemplates = clusterEnabledDiskTemplates cluster
89 72747d91 Iustin Pop
      def_hv = case hypervisors of
90 72747d91 Iustin Pop
                 x:_ -> showJSON x
91 72747d91 Iustin Pop
                 [] -> JSNull
92 25b54de0 Iustin Pop
      bits = show (bitSize (0::Int)) ++ "bits"
93 25b54de0 Iustin Pop
      arch_tuple = [bits, arch]
94 5b11f8db Iustin Pop
      obj = [ ("software_version", showJSON C.releaseVersion)
95 5b11f8db Iustin Pop
            , ("protocol_version", showJSON C.protocolVersion)
96 5b11f8db Iustin Pop
            , ("config_version", showJSON C.configVersion)
97 25b54de0 Iustin Pop
            , ("os_api_version", showJSON $ maximum C.osApiVersions)
98 5b11f8db Iustin Pop
            , ("export_version", showJSON C.exportVersion)
99 026f444f Thomas Thrainer
            , ("vcs_version", showJSON C.vcsVersion)
100 5b11f8db Iustin Pop
            , ("architecture", showJSON arch_tuple)
101 25b54de0 Iustin Pop
            , ("name", showJSON $ clusterClusterName cluster)
102 25b54de0 Iustin Pop
            , ("master", showJSON $ clusterMasterNode cluster)
103 72747d91 Iustin Pop
            , ("default_hypervisor", def_hv)
104 5b11f8db Iustin Pop
            , ("enabled_hypervisors", showJSON hypervisors)
105 a2160e57 Iustin Pop
            , ("hvparams", showJSON $ clusterHvparams cluster)
106 a2160e57 Iustin Pop
            , ("os_hvp", showJSON $ clusterOsHvp cluster)
107 25b54de0 Iustin Pop
            , ("beparams", showJSON $ clusterBeparams cluster)
108 25b54de0 Iustin Pop
            , ("osparams", showJSON $ clusterOsparams cluster)
109 25b54de0 Iustin Pop
            , ("ipolicy", showJSON $ clusterIpolicy cluster)
110 25b54de0 Iustin Pop
            , ("nicparams", showJSON $ clusterNicparams cluster)
111 25b54de0 Iustin Pop
            , ("ndparams", showJSON $ clusterNdparams cluster)
112 a2160e57 Iustin Pop
            , ("diskparams", showJSON $ clusterDiskparams cluster)
113 25b54de0 Iustin Pop
            , ("candidate_pool_size",
114 25b54de0 Iustin Pop
               showJSON $ clusterCandidatePoolSize cluster)
115 25b54de0 Iustin Pop
            , ("master_netdev",  showJSON $ clusterMasterNetdev cluster)
116 25b54de0 Iustin Pop
            , ("master_netmask", showJSON $ clusterMasterNetmask cluster)
117 25b54de0 Iustin Pop
            , ("use_external_mip_script",
118 25b54de0 Iustin Pop
               showJSON $ clusterUseExternalMipScript cluster)
119 64b0309a Dimitris Aragiorgis
            , ("volume_group_name",
120 64b0309a Dimitris Aragiorgis
               maybe JSNull showJSON (clusterVolumeGroupName cluster))
121 25b54de0 Iustin Pop
            , ("drbd_usermode_helper",
122 25b54de0 Iustin Pop
               maybe JSNull showJSON (clusterDrbdUsermodeHelper cluster))
123 25b54de0 Iustin Pop
            , ("file_storage_dir", showJSON $ clusterFileStorageDir cluster)
124 25b54de0 Iustin Pop
            , ("shared_file_storage_dir",
125 25b54de0 Iustin Pop
               showJSON $ clusterSharedFileStorageDir cluster)
126 25b54de0 Iustin Pop
            , ("maintain_node_health",
127 25b54de0 Iustin Pop
               showJSON $ clusterMaintainNodeHealth cluster)
128 25b54de0 Iustin Pop
            , ("ctime", showJSON $ clusterCtime cluster)
129 25b54de0 Iustin Pop
            , ("mtime", showJSON $ clusterMtime cluster)
130 25b54de0 Iustin Pop
            , ("uuid", showJSON $ clusterUuid cluster)
131 25b54de0 Iustin Pop
            , ("tags", showJSON $ clusterTags cluster)
132 25b54de0 Iustin Pop
            , ("uid_pool", showJSON $ clusterUidPool cluster)
133 25b54de0 Iustin Pop
            , ("default_iallocator",
134 25b54de0 Iustin Pop
               showJSON $ clusterDefaultIallocator cluster)
135 25b54de0 Iustin Pop
            , ("reserved_lvs", showJSON $ clusterReservedLvs cluster)
136 25b54de0 Iustin Pop
            , ("primary_ip_version",
137 25b54de0 Iustin Pop
               showJSON . ipFamilyToVersion $ clusterPrimaryIpFamily cluster)
138 7b9ceea7 Helga Velroyen
            , ("prealloc_wipe_disks",
139 7b9ceea7 Helga Velroyen
               showJSON $ clusterPreallocWipeDisks cluster)
140 7b9ceea7 Helga Velroyen
            , ("hidden_os", showJSON $ clusterHiddenOs cluster)
141 7b9ceea7 Helga Velroyen
            , ("blacklisted_os", showJSON $ clusterBlacklistedOs cluster)
142 966e1580 Helga Velroyen
            , ("enabled_disk_templates", showJSON diskTemplates)
143 25b54de0 Iustin Pop
            ]
144 25b54de0 Iustin Pop
145 25b54de0 Iustin Pop
  in return . Ok . J.makeObj $ obj
146 25b54de0 Iustin Pop
147 d8e7c45e Iustin Pop
handleCall cfg (QueryTags kind) =
148 f2374060 Iustin Pop
  let tags = case kind of
149 d8e7c45e Iustin Pop
               TagCluster       -> Ok . clusterTags $ configCluster cfg
150 d8e7c45e Iustin Pop
               TagGroup    name -> groupTags <$> Config.getGroup    cfg name
151 d8e7c45e Iustin Pop
               TagNode     name -> nodeTags  <$> Config.getNode     cfg name
152 d8e7c45e Iustin Pop
               TagInstance name -> instTags  <$> Config.getInstance cfg name
153 9d0b521e Dimitris Aragiorgis
               TagNetwork  name -> networkTags  <$> Config.getNetwork cfg name
154 f2374060 Iustin Pop
  in return (J.showJSON <$> tags)
155 f2374060 Iustin Pop
156 4cbe9bda Iustin Pop
handleCall cfg (Query qkind qfields qfilter) = do
157 fa2c927c Agata Murawska
  result <- query cfg True (Qlang.Query qkind qfields qfilter)
158 4cbe9bda Iustin Pop
  return $ J.showJSON <$> result
159 4cbe9bda Iustin Pop
160 518023a9 Iustin Pop
handleCall _ (QueryFields qkind qfields) = do
161 518023a9 Iustin Pop
  let result = queryFields (Qlang.QueryFields qkind qfields)
162 518023a9 Iustin Pop
  return $ J.showJSON <$> result
163 518023a9 Iustin Pop
164 cd67e337 Iustin Pop
handleCall cfg (QueryNodes names fields lock) =
165 037762a9 Iustin Pop
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNode)
166 c4e0d065 Klaus Aehlig
    (map Left names) fields lock
167 cd67e337 Iustin Pop
168 cd67e337 Iustin Pop
handleCall cfg (QueryGroups names fields lock) =
169 037762a9 Iustin Pop
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRGroup)
170 c4e0d065 Klaus Aehlig
    (map Left names) fields lock
171 cd67e337 Iustin Pop
172 a7e484c4 Iustin Pop
handleCall cfg (QueryJobs names fields) =
173 a7e484c4 Iustin Pop
  handleClassicQuery cfg (Qlang.ItemTypeLuxi Qlang.QRJob)
174 c4e0d065 Klaus Aehlig
    (map (Right . fromIntegral . fromJobId) names)  fields False
175 a7e484c4 Iustin Pop
176 795d035d Klaus Aehlig
handleCall cfg (QueryNetworks names fields lock) =
177 795d035d Klaus Aehlig
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNetwork)
178 795d035d Klaus Aehlig
    (map Left names) fields lock
179 795d035d Klaus Aehlig
180 25b54de0 Iustin Pop
handleCall _ op =
181 5183e8be Iustin Pop
  return . Bad $
182 5183e8be Iustin Pop
    GenericError ("Luxi call '" ++ strOfOp op ++ "' not implemented")
183 25b54de0 Iustin Pop
184 25b54de0 Iustin Pop
-- | Given a decoded luxi request, executes it and sends the luxi
185 25b54de0 Iustin Pop
-- response back to the client.
186 25b54de0 Iustin Pop
handleClientMsg :: Client -> ConfigReader -> LuxiOp -> IO Bool
187 25b54de0 Iustin Pop
handleClientMsg client creader args = do
188 25b54de0 Iustin Pop
  cfg <- creader
189 25b54de0 Iustin Pop
  logDebug $ "Request: " ++ show args
190 25b54de0 Iustin Pop
  call_result <- handleCallWrapper cfg args
191 25b54de0 Iustin Pop
  (!status, !rval) <-
192 25b54de0 Iustin Pop
    case call_result of
193 9abbb084 Iustin Pop
      Bad err -> do
194 3e0c2a24 Klaus Aehlig
        logWarning $ "Failed to execute request " ++ show args ++ ": "
195 3e0c2a24 Klaus Aehlig
                     ++ show err
196 5183e8be Iustin Pop
        return (False, showJSON err)
197 25b54de0 Iustin Pop
      Ok result -> do
198 f74b88fa Iustin Pop
        -- only log the first 2,000 chars of the result
199 f74b88fa Iustin Pop
        logDebug $ "Result (truncated): " ++ take 2000 (J.encode result)
200 3e0c2a24 Klaus Aehlig
        logInfo $ "Successfully handled " ++ strOfOp args
201 25b54de0 Iustin Pop
        return (True, result)
202 25b54de0 Iustin Pop
  sendMsg client $ buildResponse status rval
203 25b54de0 Iustin Pop
  return True
204 25b54de0 Iustin Pop
205 25b54de0 Iustin Pop
-- | Handles one iteration of the client protocol: receives message,
206 3e02cd3c Michele Tartara
-- checks it for validity and decodes it, returns response.
207 25b54de0 Iustin Pop
handleClient :: Client -> ConfigReader -> IO Bool
208 25b54de0 Iustin Pop
handleClient client creader = do
209 25b54de0 Iustin Pop
  !msg <- recvMsgExt client
210 385d4574 Klaus Aehlig
  logDebug $ "Received message: " ++ show msg
211 25b54de0 Iustin Pop
  case msg of
212 25b54de0 Iustin Pop
    RecvConnClosed -> logDebug "Connection closed" >> return False
213 25b54de0 Iustin Pop
    RecvError err -> logWarning ("Error during message receiving: " ++ err) >>
214 25b54de0 Iustin Pop
                     return False
215 25b54de0 Iustin Pop
    RecvOk payload ->
216 25b54de0 Iustin Pop
      case validateCall payload >>= decodeCall of
217 9abbb084 Iustin Pop
        Bad err -> do
218 9abbb084 Iustin Pop
             let errmsg = "Failed to parse request: " ++ err
219 9abbb084 Iustin Pop
             logWarning errmsg
220 9abbb084 Iustin Pop
             sendMsg client $ buildResponse False (showJSON errmsg)
221 9abbb084 Iustin Pop
             return False
222 25b54de0 Iustin Pop
        Ok args -> handleClientMsg client creader args
223 25b54de0 Iustin Pop
224 25b54de0 Iustin Pop
-- | Main client loop: runs one loop of 'handleClient', and if that
225 cb44e3db Helga Velroyen
-- doesn't report a finished (closed) connection, restarts itself.
226 25b54de0 Iustin Pop
clientLoop :: Client -> ConfigReader -> IO ()
227 25b54de0 Iustin Pop
clientLoop client creader = do
228 25b54de0 Iustin Pop
  result <- handleClient client creader
229 25b54de0 Iustin Pop
  if result
230 25b54de0 Iustin Pop
    then clientLoop client creader
231 25b54de0 Iustin Pop
    else closeClient client
232 25b54de0 Iustin Pop
233 670e954a Thomas Thrainer
-- | Main listener loop: accepts clients, forks an I/O thread to handle
234 670e954a Thomas Thrainer
-- that client.
235 670e954a Thomas Thrainer
listener :: ConfigReader -> S.Socket -> IO ()
236 670e954a Thomas Thrainer
listener creader socket = do
237 25b54de0 Iustin Pop
  client <- acceptClient socket
238 25b54de0 Iustin Pop
  _ <- forkIO $ clientLoop client creader
239 670e954a Thomas Thrainer
  return ()
240 25b54de0 Iustin Pop
241 670e954a Thomas Thrainer
-- | Type alias for prepMain results
242 670e954a Thomas Thrainer
type PrepResult = (FilePath, S.Socket, IORef (Result ConfigData))
243 670e954a Thomas Thrainer
244 3695a4e0 Thomas Thrainer
-- | Check function for luxid.
245 670e954a Thomas Thrainer
checkMain :: CheckFn ()
246 670e954a Thomas Thrainer
checkMain _ = return $ Right ()
247 670e954a Thomas Thrainer
248 3695a4e0 Thomas Thrainer
-- | Prepare function for luxid.
249 670e954a Thomas Thrainer
prepMain :: PrepFn () PrepResult
250 670e954a Thomas Thrainer
prepMain _ _ = do
251 670e954a Thomas Thrainer
  socket_path <- Path.defaultQuerySocket
252 0d0ac025 Iustin Pop
  cleanupSocket socket_path
253 73b16ca1 Iustin Pop
  s <- describeError "binding to the Luxi socket"
254 e455a3e8 Michele Tartara
         Nothing (Just socket_path) $ getServer True socket_path
255 670e954a Thomas Thrainer
  cref <- newIORef (Bad "Configuration not yet loaded")
256 670e954a Thomas Thrainer
  return (socket_path, s, cref)
257 670e954a Thomas Thrainer
258 670e954a Thomas Thrainer
-- | Main function.
259 670e954a Thomas Thrainer
main :: MainFn () PrepResult
260 670e954a Thomas Thrainer
main _ _ (socket_path, server, cref) = do
261 670e954a Thomas Thrainer
  initConfigReader id cref
262 670e954a Thomas Thrainer
  let creader = readIORef cref
263 4c3f55b8 Iustin Pop
264 4c3f55b8 Iustin Pop
  finally
265 670e954a Thomas Thrainer
    (forever $ listener creader server)
266 4c3f55b8 Iustin Pop
    (closeServer socket_path server)