root / src / Ganeti / Query / Server.hs @ 72747d91
History | View | Annotate | Download (9.7 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 |
( ConfigReader |
30 |
, prepQueryD |
31 |
, runQueryD |
32 |
) where |
33 |
|
34 |
import Control.Applicative |
35 |
import Control.Concurrent |
36 |
import Control.Exception |
37 |
import Data.Bits (bitSize) |
38 |
import Data.Maybe |
39 |
import qualified Network.Socket as S |
40 |
import qualified Text.JSON as J |
41 |
import Text.JSON (showJSON, JSValue(..)) |
42 |
import System.Info (arch) |
43 |
|
44 |
import qualified Ganeti.Constants as C |
45 |
import Ganeti.Errors |
46 |
import qualified Ganeti.Path as Path |
47 |
import Ganeti.Daemon |
48 |
import Ganeti.Objects |
49 |
import qualified Ganeti.Config as Config |
50 |
import Ganeti.BasicTypes |
51 |
import Ganeti.Logging |
52 |
import Ganeti.Luxi |
53 |
import Ganeti.OpCodes (TagObject(..)) |
54 |
import qualified Ganeti.Query.Language as Qlang |
55 |
import Ganeti.Query.Query |
56 |
import Ganeti.Query.Filter (makeSimpleFilter) |
57 |
|
58 |
-- | A type for functions that can return the configuration when |
59 |
-- executed. |
60 |
type ConfigReader = IO (Result ConfigData) |
61 |
|
62 |
-- | Helper for classic queries. |
63 |
handleClassicQuery :: ConfigData -- ^ Cluster config |
64 |
-> Qlang.ItemType -- ^ Query type |
65 |
-> [Either String Integer] -- ^ Requested names |
66 |
-- (empty means all) |
67 |
-> [String] -- ^ Requested fields |
68 |
-> Bool -- ^ Whether to do sync queries or not |
69 |
-> IO (GenericResult GanetiException JSValue) |
70 |
handleClassicQuery _ _ _ _ True = |
71 |
return . Bad $ OpPrereqError "Sync queries are not allowed" ECodeInval |
72 |
handleClassicQuery cfg qkind names fields _ = do |
73 |
let flt = makeSimpleFilter (nameField qkind) names |
74 |
qr <- query cfg True (Qlang.Query qkind fields flt) |
75 |
return $ showJSON <$> (qr >>= queryCompat) |
76 |
|
77 |
-- | Minimal wrapper to handle the missing config case. |
78 |
handleCallWrapper :: Result ConfigData -> LuxiOp -> IO (ErrorResult JSValue) |
79 |
handleCallWrapper (Bad msg) _ = |
80 |
return . Bad . ConfigurationError $ |
81 |
"I do not have access to a valid configuration, cannot\ |
82 |
\ process queries: " ++ msg |
83 |
handleCallWrapper (Ok config) op = handleCall config op |
84 |
|
85 |
-- | Actual luxi operation handler. |
86 |
handleCall :: ConfigData -> LuxiOp -> IO (ErrorResult JSValue) |
87 |
handleCall cdata QueryClusterInfo = |
88 |
let cluster = configCluster cdata |
89 |
hypervisors = clusterEnabledHypervisors cluster |
90 |
def_hv = case hypervisors of |
91 |
x:_ -> showJSON x |
92 |
[] -> JSNull |
93 |
bits = show (bitSize (0::Int)) ++ "bits" |
94 |
arch_tuple = [bits, arch] |
95 |
obj = [ ("software_version", showJSON C.releaseVersion) |
96 |
, ("protocol_version", showJSON C.protocolVersion) |
97 |
, ("config_version", showJSON C.configVersion) |
98 |
, ("os_api_version", showJSON $ maximum C.osApiVersions) |
99 |
, ("export_version", showJSON C.exportVersion) |
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", showJSON $ clusterVolumeGroupName cluster) |
120 |
, ("drbd_usermode_helper", |
121 |
maybe JSNull showJSON (clusterDrbdUsermodeHelper cluster)) |
122 |
, ("file_storage_dir", showJSON $ clusterFileStorageDir cluster) |
123 |
, ("shared_file_storage_dir", |
124 |
showJSON $ clusterSharedFileStorageDir cluster) |
125 |
, ("maintain_node_health", |
126 |
showJSON $ clusterMaintainNodeHealth cluster) |
127 |
, ("ctime", showJSON $ clusterCtime cluster) |
128 |
, ("mtime", showJSON $ clusterMtime cluster) |
129 |
, ("uuid", showJSON $ clusterUuid cluster) |
130 |
, ("tags", showJSON $ clusterTags cluster) |
131 |
, ("uid_pool", showJSON $ clusterUidPool cluster) |
132 |
, ("default_iallocator", |
133 |
showJSON $ clusterDefaultIallocator cluster) |
134 |
, ("reserved_lvs", showJSON $ clusterReservedLvs cluster) |
135 |
, ("primary_ip_version", |
136 |
showJSON . ipFamilyToVersion $ clusterPrimaryIpFamily cluster) |
137 |
, ("prealloc_wipe_disks", |
138 |
showJSON $ clusterPreallocWipeDisks cluster) |
139 |
, ("hidden_os", showJSON $ clusterHiddenOs cluster) |
140 |
, ("blacklisted_os", showJSON $ clusterBlacklistedOs cluster) |
141 |
] |
142 |
|
143 |
in return . Ok . J.makeObj $ obj |
144 |
|
145 |
handleCall cfg (QueryTags kind) = |
146 |
let tags = case kind of |
147 |
TagCluster -> Ok . clusterTags $ configCluster cfg |
148 |
TagGroup name -> groupTags <$> Config.getGroup cfg name |
149 |
TagNode name -> nodeTags <$> Config.getNode cfg name |
150 |
TagInstance name -> instTags <$> Config.getInstance cfg name |
151 |
in return (J.showJSON <$> tags) |
152 |
|
153 |
handleCall cfg (Query qkind qfields qfilter) = do |
154 |
result <- query cfg True (Qlang.Query qkind qfields qfilter) |
155 |
return $ J.showJSON <$> result |
156 |
|
157 |
handleCall _ (QueryFields qkind qfields) = do |
158 |
let result = queryFields (Qlang.QueryFields qkind qfields) |
159 |
return $ J.showJSON <$> result |
160 |
|
161 |
handleCall cfg (QueryNodes names fields lock) = |
162 |
handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRNode) |
163 |
(map Left names) fields lock |
164 |
|
165 |
handleCall cfg (QueryGroups names fields lock) = |
166 |
handleClassicQuery cfg (Qlang.ItemTypeOpCode Qlang.QRGroup) |
167 |
(map Left names) fields lock |
168 |
|
169 |
handleCall cfg (QueryJobs names fields) = |
170 |
handleClassicQuery cfg (Qlang.ItemTypeLuxi Qlang.QRJob) |
171 |
(map (Right . fromIntegral . fromJobId) names) fields False |
172 |
|
173 |
handleCall _ op = |
174 |
return . Bad $ |
175 |
GenericError ("Luxi call '" ++ strOfOp op ++ "' not implemented") |
176 |
|
177 |
|
178 |
-- | Given a decoded luxi request, executes it and sends the luxi |
179 |
-- response back to the client. |
180 |
handleClientMsg :: Client -> ConfigReader -> LuxiOp -> IO Bool |
181 |
handleClientMsg client creader args = do |
182 |
cfg <- creader |
183 |
logDebug $ "Request: " ++ show args |
184 |
call_result <- handleCallWrapper cfg args |
185 |
(!status, !rval) <- |
186 |
case call_result of |
187 |
Bad err -> do |
188 |
logWarning $ "Failed to execute request: " ++ show err |
189 |
return (False, showJSON err) |
190 |
Ok result -> do |
191 |
-- only log the first 2,000 chars of the result |
192 |
logDebug $ "Result (truncated): " ++ take 2000 (J.encode result) |
193 |
return (True, result) |
194 |
sendMsg client $ buildResponse status rval |
195 |
return True |
196 |
|
197 |
-- | Handles one iteration of the client protocol: receives message, |
198 |
-- checks for validity and decods, returns response. |
199 |
handleClient :: Client -> ConfigReader -> IO Bool |
200 |
handleClient client creader = do |
201 |
!msg <- recvMsgExt client |
202 |
case msg of |
203 |
RecvConnClosed -> logDebug "Connection closed" >> return False |
204 |
RecvError err -> logWarning ("Error during message receiving: " ++ err) >> |
205 |
return False |
206 |
RecvOk payload -> |
207 |
case validateCall payload >>= decodeCall of |
208 |
Bad err -> do |
209 |
let errmsg = "Failed to parse request: " ++ err |
210 |
logWarning errmsg |
211 |
sendMsg client $ buildResponse False (showJSON errmsg) |
212 |
return False |
213 |
Ok args -> handleClientMsg client creader args |
214 |
|
215 |
-- | Main client loop: runs one loop of 'handleClient', and if that |
216 |
-- doesn't repot a finished (closed) connection, restarts itself. |
217 |
clientLoop :: Client -> ConfigReader -> IO () |
218 |
clientLoop client creader = do |
219 |
result <- handleClient client creader |
220 |
if result |
221 |
then clientLoop client creader |
222 |
else closeClient client |
223 |
|
224 |
-- | Main loop: accepts clients, forks an I/O thread to handle that |
225 |
-- client, and then restarts. |
226 |
mainLoop :: ConfigReader -> S.Socket -> IO () |
227 |
mainLoop creader socket = do |
228 |
client <- acceptClient socket |
229 |
_ <- forkIO $ clientLoop client creader |
230 |
mainLoop creader socket |
231 |
|
232 |
-- | Function that prepares the server socket. |
233 |
prepQueryD :: Maybe FilePath -> IO (FilePath, S.Socket) |
234 |
prepQueryD fpath = do |
235 |
def_socket <- Path.defaultQuerySocket |
236 |
let socket_path = fromMaybe def_socket fpath |
237 |
cleanupSocket socket_path |
238 |
s <- describeError "binding to the Luxi socket" |
239 |
Nothing (Just socket_path) $ getServer socket_path |
240 |
return (socket_path, s) |
241 |
|
242 |
-- | Main function that runs the query endpoint. |
243 |
runQueryD :: (FilePath, S.Socket) -> ConfigReader -> IO () |
244 |
runQueryD (socket_path, server) creader = |
245 |
finally |
246 |
(mainLoop creader server) |
247 |
(closeServer socket_path server) |