Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (10.4 kB)

1
{-# LANGUAGE BangPatterns #-}
2

    
3
{-| Implementation of the Ganeti Query2 server.
4

    
5
-}
6

    
7
{-
8

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

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

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

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

    
26
-}
27

    
28
module Ganeti.Query.Server
29
  ( main
30
  , checkMain
31
  , prepMain
32
  ) where
33

    
34
import Control.Applicative
35
import Control.Concurrent
36
import Control.Exception
37
import Control.Monad (forever)
38
import Data.Bits (bitSize)
39
import Data.IORef
40
import qualified Network.Socket as S
41
import qualified Text.JSON as J
42
import Text.JSON (showJSON, JSValue(..))
43
import System.Info (arch)
44

    
45
import qualified Ganeti.Constants as C
46
import Ganeti.Errors
47
import qualified Ganeti.Path as Path
48
import Ganeti.Daemon
49
import Ganeti.Objects
50
import qualified Ganeti.Config as Config
51
import Ganeti.ConfigReader
52
import Ganeti.BasicTypes
53
import Ganeti.Logging
54
import Ganeti.Luxi
55
import Ganeti.OpCodes (TagObject(..))
56
import qualified Ganeti.Query.Language as Qlang
57
import Ganeti.Query.Query
58
import Ganeti.Query.Filter (makeSimpleFilter)
59

    
60
-- | Helper for classic queries.
61
handleClassicQuery :: ConfigData      -- ^ Cluster config
62
                   -> Qlang.ItemType  -- ^ Query type
63
                   -> [Either String Integer] -- ^ Requested names
64
                                              -- (empty means all)
65
                   -> [String]        -- ^ Requested fields
66
                   -> Bool            -- ^ Whether to do sync queries or not
67
                   -> IO (GenericResult GanetiException JSValue)
68
handleClassicQuery _ _ _ _ True =
69
  return . Bad $ OpPrereqError "Sync queries are not allowed" ECodeInval
70
handleClassicQuery cfg qkind names fields _ = do
71
  let flt = makeSimpleFilter (nameField qkind) names
72
  qr <- query cfg True (Qlang.Query qkind fields flt)
73
  return $ showJSON <$> (qr >>= queryCompat)
74

    
75
-- | Minimal wrapper to handle the missing config case.
76
handleCallWrapper :: Result ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
77
handleCallWrapper (Bad msg) _ =
78
  return . Bad . ConfigurationError $
79
           "I do not have access to a valid configuration, cannot\
80
           \ process queries: " ++ msg
81
handleCallWrapper (Ok config) op = handleCall config op
82

    
83
-- | Actual luxi operation handler.
84
handleCall :: ConfigData -> LuxiOp -> IO (ErrorResult JSValue)
85
handleCall cdata QueryClusterInfo =
86
  let cluster = configCluster cdata
87
      hypervisors = clusterEnabledHypervisors cluster
88
      diskTemplates = clusterEnabledDiskTemplates cluster
89
      def_hv = case hypervisors of
90
                 x:_ -> showJSON x
91
                 [] -> JSNull
92
      bits = show (bitSize (0::Int)) ++ "bits"
93
      arch_tuple = [bits, arch]
94
      obj = [ ("software_version", showJSON C.releaseVersion)
95
            , ("protocol_version", showJSON C.protocolVersion)
96
            , ("config_version", showJSON C.configVersion)
97
            , ("os_api_version", showJSON $ maximum C.osApiVersions)
98
            , ("export_version", showJSON C.exportVersion)
99
            , ("vcs_version", showJSON C.vcsVersion)
100
            , ("architecture", showJSON arch_tuple)
101
            , ("name", showJSON $ clusterClusterName cluster)
102
            , ("master", showJSON $ clusterMasterNode cluster)
103
            , ("default_hypervisor", def_hv)
104
            , ("enabled_hypervisors", showJSON hypervisors)
105
            , ("hvparams", showJSON $ clusterHvparams cluster)
106
            , ("os_hvp", showJSON $ clusterOsHvp cluster)
107
            , ("beparams", showJSON $ clusterBeparams cluster)
108
            , ("osparams", showJSON $ clusterOsparams cluster)
109
            , ("ipolicy", showJSON $ clusterIpolicy cluster)
110
            , ("nicparams", showJSON $ clusterNicparams cluster)
111
            , ("ndparams", showJSON $ clusterNdparams cluster)
112
            , ("diskparams", showJSON $ clusterDiskparams cluster)
113
            , ("candidate_pool_size",
114
               showJSON $ clusterCandidatePoolSize cluster)
115
            , ("master_netdev",  showJSON $ clusterMasterNetdev cluster)
116
            , ("master_netmask", showJSON $ clusterMasterNetmask cluster)
117
            , ("use_external_mip_script",
118
               showJSON $ clusterUseExternalMipScript cluster)
119
            , ("volume_group_name",
120
               maybe JSNull showJSON (clusterVolumeGroupName cluster))
121
            , ("drbd_usermode_helper",
122
               maybe JSNull showJSON (clusterDrbdUsermodeHelper cluster))
123
            , ("file_storage_dir", showJSON $ clusterFileStorageDir cluster)
124
            , ("shared_file_storage_dir",
125
               showJSON $ clusterSharedFileStorageDir cluster)
126
            , ("maintain_node_health",
127
               showJSON $ clusterMaintainNodeHealth cluster)
128
            , ("ctime", showJSON $ clusterCtime cluster)
129
            , ("mtime", showJSON $ clusterMtime cluster)
130
            , ("uuid", showJSON $ clusterUuid cluster)
131
            , ("tags", showJSON $ clusterTags cluster)
132
            , ("uid_pool", showJSON $ clusterUidPool cluster)
133
            , ("default_iallocator",
134
               showJSON $ clusterDefaultIallocator cluster)
135
            , ("reserved_lvs", showJSON $ clusterReservedLvs cluster)
136
            , ("primary_ip_version",
137
               showJSON . ipFamilyToVersion $ clusterPrimaryIpFamily cluster)
138
            , ("prealloc_wipe_disks",
139
               showJSON $ clusterPreallocWipeDisks cluster)
140
            , ("hidden_os", showJSON $ clusterHiddenOs cluster)
141
            , ("blacklisted_os", showJSON $ clusterBlacklistedOs cluster)
142
            , ("enabled_disk_templates", showJSON diskTemplates)
143
            ]
144

    
145
  in return . Ok . J.makeObj $ obj
146

    
147
handleCall cfg (QueryTags kind) =
148
  let tags = case kind of
149
               TagCluster       -> Ok . clusterTags $ configCluster cfg
150
               TagGroup    name -> groupTags <$> Config.getGroup    cfg name
151
               TagNode     name -> nodeTags  <$> Config.getNode     cfg name
152
               TagInstance name -> instTags  <$> Config.getInstance cfg name
153
               TagNetwork  name -> networkTags  <$> Config.getNetwork cfg name
154
  in return (J.showJSON <$> tags)
155

    
156
handleCall cfg (Query qkind qfields qfilter) = do
157
  result <- query cfg True (Qlang.Query qkind qfields qfilter)
158
  return $ J.showJSON <$> result
159

    
160
handleCall _ (QueryFields qkind qfields) = do
161
  let result = queryFields (Qlang.QueryFields qkind qfields)
162
  return $ J.showJSON <$> result
163

    
164
handleCall cfg (QueryNodes names fields lock) =
165
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNode)
166
    (map Left names) fields lock
167

    
168
handleCall cfg (QueryGroups names fields lock) =
169
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRGroup)
170
    (map Left names) fields lock
171

    
172
handleCall cfg (QueryJobs names fields) =
173
  handleClassicQuery cfg (Qlang.ItemTypeLuxi Qlang.QRJob)
174
    (map (Right . fromIntegral . fromJobId) names)  fields False
175

    
176
handleCall cfg (QueryNetworks names fields lock) =
177
  handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNetwork)
178
    (map Left names) fields lock
179

    
180
handleCall _ op =
181
  return . Bad $
182
    GenericError ("Luxi call '" ++ strOfOp op ++ "' not implemented")
183

    
184
-- | Given a decoded luxi request, executes it and sends the luxi
185
-- response back to the client.
186
handleClientMsg :: Client -> ConfigReader -> LuxiOp -> IO Bool
187
handleClientMsg client creader args = do
188
  cfg <- creader
189
  logDebug $ "Request: " ++ show args
190
  call_result <- handleCallWrapper cfg args
191
  (!status, !rval) <-
192
    case call_result of
193
      Bad err -> do
194
        logWarning $ "Failed to execute request " ++ show args ++ ": "
195
                     ++ show err
196
        return (False, showJSON err)
197
      Ok result -> do
198
        -- only log the first 2,000 chars of the result
199
        logDebug $ "Result (truncated): " ++ take 2000 (J.encode result)
200
        logInfo $ "Successfully handled " ++ strOfOp args
201
        return (True, result)
202
  sendMsg client $ buildResponse status rval
203
  return True
204

    
205
-- | Handles one iteration of the client protocol: receives message,
206
-- checks it for validity and decodes it, returns response.
207
handleClient :: Client -> ConfigReader -> IO Bool
208
handleClient client creader = do
209
  !msg <- recvMsgExt client
210
  logDebug $ "Received message: " ++ show msg
211
  case msg of
212
    RecvConnClosed -> logDebug "Connection closed" >> return False
213
    RecvError err -> logWarning ("Error during message receiving: " ++ err) >>
214
                     return False
215
    RecvOk payload ->
216
      case validateCall payload >>= decodeCall of
217
        Bad err -> do
218
             let errmsg = "Failed to parse request: " ++ err
219
             logWarning errmsg
220
             sendMsg client $ buildResponse False (showJSON errmsg)
221
             return False
222
        Ok args -> handleClientMsg client creader args
223

    
224
-- | Main client loop: runs one loop of 'handleClient', and if that
225
-- doesn't report a finished (closed) connection, restarts itself.
226
clientLoop :: Client -> ConfigReader -> IO ()
227
clientLoop client creader = do
228
  result <- handleClient client creader
229
  if result
230
    then clientLoop client creader
231
    else closeClient client
232

    
233
-- | Main listener loop: accepts clients, forks an I/O thread to handle
234
-- that client.
235
listener :: ConfigReader -> S.Socket -> IO ()
236
listener creader socket = do
237
  client <- acceptClient socket
238
  _ <- forkIO $ clientLoop client creader
239
  return ()
240

    
241
-- | Type alias for prepMain results
242
type PrepResult = (FilePath, S.Socket, IORef (Result ConfigData))
243

    
244
-- | Check function for luxid.
245
checkMain :: CheckFn ()
246
checkMain _ = return $ Right ()
247

    
248
-- | Prepare function for luxid.
249
prepMain :: PrepFn () PrepResult
250
prepMain _ _ = do
251
  socket_path <- Path.defaultQuerySocket
252
  cleanupSocket socket_path
253
  s <- describeError "binding to the Luxi socket"
254
         Nothing (Just socket_path) $ getServer True socket_path
255
  cref <- newIORef (Bad "Configuration not yet loaded")
256
  return (socket_path, s, cref)
257

    
258
-- | Main function.
259
main :: MainFn () PrepResult
260
main _ _ (socket_path, server, cref) = do
261
  initConfigReader id cref
262
  let creader = readIORef cref
263

    
264
  finally
265
    (forever $ listener creader server)
266
    (closeServer socket_path server)