root / src / Ganeti / Query / Query.hs @ 5771c501
History | View | Annotate | Download (13.7 kB)
1 |
{-| Implementation of the Ganeti Query2 functionality. |
---|---|
2 |
|
3 |
-} |
4 |
|
5 |
{- |
6 |
|
7 |
Copyright (C) 2012, 2013 Google Inc. |
8 |
|
9 |
This program is free software; you can redistribute it and/or modify |
10 |
it under the terms of the GNU General Public License as published by |
11 |
the Free Software Foundation; either version 2 of the License, or |
12 |
(at your option) any later version. |
13 |
|
14 |
This program is distributed in the hope that it will be useful, but |
15 |
WITHOUT ANY WARRANTY; without even the implied warranty of |
16 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
17 |
General Public License for more details. |
18 |
|
19 |
You should have received a copy of the GNU General Public License |
20 |
along with this program; if not, write to the Free Software |
21 |
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
22 |
02110-1301, USA. |
23 |
|
24 |
-} |
25 |
|
26 |
{- |
27 |
|
28 |
TODO: problems with the current model: |
29 |
|
30 |
1. There's nothing preventing a result such as ResultEntry RSNormal |
31 |
Nothing, or ResultEntry RSNoData (Just ...); ideally, we would |
32 |
separate the the RSNormal and other types; we would need a new data |
33 |
type for this, though, with JSON encoding/decoding |
34 |
|
35 |
2. We don't have a way to 'bind' a FieldDefinition's field type |
36 |
(e.q. QFTBool) with the actual value that is returned from a |
37 |
FieldGetter. This means that the various getter functions can return |
38 |
divergent types for the same field when evaluated against multiple |
39 |
items. This is bad; it only works today because we 'hide' everything |
40 |
behind JSValue, but is not nice at all. We should probably remove the |
41 |
separation between FieldDefinition and the FieldGetter, and introduce |
42 |
a new abstract data type, similar to QFT*, that contains the values |
43 |
too. |
44 |
|
45 |
-} |
46 |
|
47 |
module Ganeti.Query.Query |
48 |
( query |
49 |
, queryFields |
50 |
, queryCompat |
51 |
, getRequestedNames |
52 |
, nameField |
53 |
) where |
54 |
|
55 |
import Control.DeepSeq |
56 |
import Control.Monad (filterM, foldM) |
57 |
import Control.Monad.Trans (lift) |
58 |
import Data.List (intercalate) |
59 |
import Data.Maybe (fromMaybe) |
60 |
import qualified Data.Map as Map |
61 |
import qualified Text.JSON as J |
62 |
|
63 |
import Ganeti.BasicTypes |
64 |
import Ganeti.Config |
65 |
import Ganeti.Errors |
66 |
import Ganeti.JQueue |
67 |
import Ganeti.JSON |
68 |
import Ganeti.Objects |
69 |
import Ganeti.Query.Common |
70 |
import qualified Ganeti.Query.Export as Export |
71 |
import Ganeti.Query.Filter |
72 |
import qualified Ganeti.Query.Job as Query.Job |
73 |
import qualified Ganeti.Query.Group as Group |
74 |
import Ganeti.Query.Language |
75 |
import qualified Ganeti.Query.Network as Network |
76 |
import qualified Ganeti.Query.Node as Node |
77 |
import Ganeti.Query.Types |
78 |
import Ganeti.Path |
79 |
import Ganeti.Types |
80 |
import Ganeti.Utils |
81 |
|
82 |
-- * Helper functions |
83 |
|
84 |
-- | Builds an unknown field definition. |
85 |
mkUnknownFDef :: String -> FieldData a b |
86 |
mkUnknownFDef name = |
87 |
( FieldDefinition name name QFTUnknown ("Unknown field '" ++ name ++ "'") |
88 |
, FieldUnknown |
89 |
, QffNormal ) |
90 |
|
91 |
-- | Runs a field getter on the existing contexts. |
92 |
execGetter :: ConfigData -> b -> a -> FieldGetter a b -> ResultEntry |
93 |
execGetter _ _ item (FieldSimple getter) = getter item |
94 |
execGetter cfg _ item (FieldConfig getter) = getter cfg item |
95 |
execGetter _ rt item (FieldRuntime getter) = getter rt item |
96 |
execGetter _ _ _ FieldUnknown = rsUnknown |
97 |
|
98 |
-- * Main query execution |
99 |
|
100 |
-- | Helper to build the list of requested fields. This transforms the |
101 |
-- list of string fields to a list of field defs and getters, with |
102 |
-- some of them possibly being unknown fields. |
103 |
getSelectedFields :: FieldMap a b -- ^ Defined fields |
104 |
-> [String] -- ^ Requested fields |
105 |
-> FieldList a b -- ^ Selected fields |
106 |
getSelectedFields defined = |
107 |
map (\name -> fromMaybe (mkUnknownFDef name) $ name `Map.lookup` defined) |
108 |
|
109 |
-- | Check whether list of queried fields contains live fields. |
110 |
needsLiveData :: [FieldGetter a b] -> Bool |
111 |
needsLiveData = any isRuntimeField |
112 |
|
113 |
-- | Checks whether we have requested exactly some names. This is a |
114 |
-- simple wrapper over 'requestedNames' and 'nameField'. |
115 |
needsNames :: Query -> Maybe [FilterValue] |
116 |
needsNames (Query kind _ qfilter) = requestedNames (nameField kind) qfilter |
117 |
|
118 |
-- | Computes the name field for different query types. |
119 |
nameField :: ItemType -> FilterField |
120 |
nameField (ItemTypeLuxi QRJob) = "id" |
121 |
nameField (ItemTypeOpCode QRExport) = "node" |
122 |
nameField _ = "name" |
123 |
|
124 |
-- | Extracts all quoted strings from a list, ignoring the |
125 |
-- 'NumericValue' entries. |
126 |
getAllQuotedStrings :: [FilterValue] -> [String] |
127 |
getAllQuotedStrings = |
128 |
concatMap extractor |
129 |
where extractor (NumericValue _) = [] |
130 |
extractor (QuotedString val) = [val] |
131 |
|
132 |
-- | Checks that we have either requested a valid set of names, or we |
133 |
-- have a more complex filter. |
134 |
getRequestedNames :: Query -> [String] |
135 |
getRequestedNames qry = |
136 |
case needsNames qry of |
137 |
Just names -> getAllQuotedStrings names |
138 |
Nothing -> [] |
139 |
|
140 |
-- | Compute the requested job IDs. This is custom since we need to |
141 |
-- handle both strings and integers. |
142 |
getRequestedJobIDs :: Filter FilterField -> Result [JobId] |
143 |
getRequestedJobIDs qfilter = |
144 |
case requestedNames (nameField (ItemTypeLuxi QRJob)) qfilter of |
145 |
Nothing -> Ok [] |
146 |
Just [] -> Ok [] |
147 |
Just vals -> |
148 |
mapM (\e -> case e of |
149 |
QuotedString s -> makeJobIdS s |
150 |
NumericValue i -> makeJobId $ fromIntegral i |
151 |
) vals |
152 |
|
153 |
-- | Generic query implementation for resources that are backed by |
154 |
-- some configuration objects. |
155 |
-- |
156 |
-- Different query types use the same 'genericQuery' function by providing |
157 |
-- a collector function and a field map. The collector function retrieves |
158 |
-- live data, and the field map provides both the requirements and the logic |
159 |
-- necessary to retrieve the data needed for the field. |
160 |
-- |
161 |
-- The 'b' type in the specification is the runtime. Every query can gather |
162 |
-- additional live data related to the configuration object using the collector |
163 |
-- to perform RPC calls. |
164 |
-- |
165 |
-- The gathered data, or the failure to get it, is expressed through a runtime |
166 |
-- object. The type of a runtime object is determined by every query type for |
167 |
-- itself, and used exclusively by that query. |
168 |
genericQuery :: FieldMap a b -- ^ Field map |
169 |
-> (Bool -> ConfigData -> [a] -> IO [(a, b)]) -- ^ Collector |
170 |
-> (a -> String) -- ^ Object to name function |
171 |
-> (ConfigData -> Container a) -- ^ Get all objects from config |
172 |
-> (ConfigData -> String -> ErrorResult a) -- ^ Lookup object |
173 |
-> ConfigData -- ^ The config to run the query against |
174 |
-> Bool -- ^ Whether the query should be run live |
175 |
-> [String] -- ^ List of requested fields |
176 |
-> Filter FilterField -- ^ Filter field |
177 |
-> [String] -- ^ List of requested names |
178 |
-> IO (ErrorResult QueryResult) |
179 |
genericQuery fieldsMap collector nameFn configFn getFn cfg |
180 |
live fields qfilter wanted = |
181 |
runResultT $ do |
182 |
cfilter <- resultT $ compileFilter fieldsMap qfilter |
183 |
let selected = getSelectedFields fieldsMap fields |
184 |
(fdefs, fgetters, _) = unzip3 selected |
185 |
live' = live && needsLiveData fgetters |
186 |
objects <- resultT $ case wanted of |
187 |
[] -> Ok . niceSortKey nameFn . |
188 |
Map.elems . fromContainer $ configFn cfg |
189 |
_ -> mapM (getFn cfg) wanted |
190 |
-- runs first pass of the filter, without a runtime context; this |
191 |
-- will limit the objects that we'll contact for exports |
192 |
fobjects <- resultT $ filterM (\n -> evaluateFilter cfg Nothing n cfilter) |
193 |
objects |
194 |
-- here run the runtime data gathering... |
195 |
runtimes <- lift $ collector live' cfg fobjects |
196 |
-- ... then filter again the results, based on gathered runtime data |
197 |
let fdata = map (\(obj, runtime) -> |
198 |
map (execGetter cfg runtime obj) fgetters) |
199 |
runtimes |
200 |
return QueryResult { qresFields = fdefs, qresData = fdata } |
201 |
|
202 |
-- | Main query execution function. |
203 |
query :: ConfigData -- ^ The current configuration |
204 |
-> Bool -- ^ Whether to collect live data |
205 |
-> Query -- ^ The query (item, fields, filter) |
206 |
-> IO (ErrorResult QueryResult) -- ^ Result |
207 |
query cfg live (Query (ItemTypeLuxi QRJob) fields qfilter) = |
208 |
queryJobs cfg live fields qfilter |
209 |
query cfg live qry = queryInner cfg live qry $ getRequestedNames qry |
210 |
|
211 |
-- | Inner query execution function. |
212 |
queryInner :: ConfigData -- ^ The current configuration |
213 |
-> Bool -- ^ Whether to collect live data |
214 |
-> Query -- ^ The query (item, fields, filter) |
215 |
-> [String] -- ^ Requested names |
216 |
-> IO (ErrorResult QueryResult) -- ^ Result |
217 |
|
218 |
queryInner cfg live (Query (ItemTypeOpCode QRNode) fields qfilter) wanted = |
219 |
genericQuery Node.fieldsMap Node.collectLiveData nodeName configNodes getNode |
220 |
cfg live fields qfilter wanted |
221 |
|
222 |
queryInner cfg live (Query (ItemTypeOpCode QRGroup) fields qfilter) wanted = |
223 |
genericQuery Group.fieldsMap Group.collectLiveData groupName configNodegroups |
224 |
getGroup cfg live fields qfilter wanted |
225 |
|
226 |
queryInner cfg live (Query (ItemTypeOpCode QRNetwork) fields qfilter) wanted = |
227 |
genericQuery Network.fieldsMap Network.collectLiveData |
228 |
(fromNonEmpty . networkName) |
229 |
configNetworks getNetwork cfg live fields qfilter wanted |
230 |
|
231 |
queryInner cfg live (Query (ItemTypeOpCode QRExport) fields qfilter) wanted = |
232 |
genericQuery Export.fieldsMap Export.collectLiveData nodeName configNodes |
233 |
getNode cfg live fields qfilter wanted |
234 |
|
235 |
queryInner _ _ (Query qkind _ _) _ = |
236 |
return . Bad . GenericError $ "Query '" ++ show qkind ++ "' not supported" |
237 |
|
238 |
-- | Query jobs specific query function, needed as we need to accept |
239 |
-- both 'QuotedString' and 'NumericValue' as wanted names. |
240 |
queryJobs :: ConfigData -- ^ The current configuration |
241 |
-> Bool -- ^ Whether to collect live data |
242 |
-> [FilterField] -- ^ Item |
243 |
-> Filter FilterField -- ^ Filter |
244 |
-> IO (ErrorResult QueryResult) -- ^ Result |
245 |
queryJobs cfg live fields qfilter = |
246 |
runResultT $ do |
247 |
rootdir <- lift queueDir |
248 |
let wanted_names = getRequestedJobIDs qfilter |
249 |
want_arch = Query.Job.wantArchived fields |
250 |
rjids <- case wanted_names of |
251 |
Bad msg -> resultT . Bad $ GenericError msg |
252 |
Ok [] -> if live |
253 |
-- we can check the filesystem for actual jobs |
254 |
then do |
255 |
maybeJobIDs <- |
256 |
lift (determineJobDirectories rootdir want_arch |
257 |
>>= getJobIDs) |
258 |
case maybeJobIDs of |
259 |
Left e -> (resultT . Bad) . BlockDeviceError $ |
260 |
"Unable to fetch the job list: " ++ show e |
261 |
Right jobIDs -> resultT . Ok $ sortJobIDs jobIDs |
262 |
-- else we shouldn't look at the filesystem... |
263 |
else return [] |
264 |
Ok v -> resultT $ Ok v |
265 |
cfilter <- resultT $ compileFilter Query.Job.fieldsMap qfilter |
266 |
let selected = getSelectedFields Query.Job.fieldsMap fields |
267 |
(fdefs, fgetters, _) = unzip3 selected |
268 |
live' = live && needsLiveData fgetters |
269 |
disabled_data = Bad "live data disabled" |
270 |
-- runs first pass of the filter, without a runtime context; this |
271 |
-- will limit the jobs that we'll load from disk |
272 |
jids <- resultT $ |
273 |
filterM (\jid -> evaluateFilter cfg Nothing jid cfilter) rjids |
274 |
-- here we run the runtime data gathering, filtering and evaluation, |
275 |
-- all in the same step, so that we don't keep jobs in memory longer |
276 |
-- than we need; we can't be fully lazy due to the multiple monad |
277 |
-- wrapping across different steps |
278 |
qdir <- lift queueDir |
279 |
fdata <- foldM |
280 |
-- big lambda, but we use many variables from outside it... |
281 |
(\lst jid -> do |
282 |
job <- lift $ if live' |
283 |
then loadJobFromDisk qdir True jid |
284 |
else return disabled_data |
285 |
pass <- resultT $ evaluateFilter cfg (Just job) jid cfilter |
286 |
let nlst = if pass |
287 |
then let row = map (execGetter cfg job jid) fgetters |
288 |
in rnf row `seq` row:lst |
289 |
else lst |
290 |
-- evaluate nlst (to WHNF), otherwise we're too lazy |
291 |
return $! nlst |
292 |
) [] jids |
293 |
return QueryResult { qresFields = fdefs, qresData = reverse fdata } |
294 |
|
295 |
-- | Helper for 'queryFields'. |
296 |
fieldsExtractor :: FieldMap a b -> [FilterField] -> QueryFieldsResult |
297 |
fieldsExtractor fieldsMap fields = |
298 |
let selected = if null fields |
299 |
then map snd $ Map.toAscList fieldsMap |
300 |
else getSelectedFields fieldsMap fields |
301 |
in QueryFieldsResult (map (\(defs, _, _) -> defs) selected) |
302 |
|
303 |
-- | Query fields call. |
304 |
queryFields :: QueryFields -> ErrorResult QueryFieldsResult |
305 |
queryFields (QueryFields (ItemTypeOpCode QRNode) fields) = |
306 |
Ok $ fieldsExtractor Node.fieldsMap fields |
307 |
|
308 |
queryFields (QueryFields (ItemTypeOpCode QRGroup) fields) = |
309 |
Ok $ fieldsExtractor Group.fieldsMap fields |
310 |
|
311 |
queryFields (QueryFields (ItemTypeOpCode QRNetwork) fields) = |
312 |
Ok $ fieldsExtractor Network.fieldsMap fields |
313 |
|
314 |
queryFields (QueryFields (ItemTypeLuxi QRJob) fields) = |
315 |
Ok $ fieldsExtractor Query.Job.fieldsMap fields |
316 |
|
317 |
queryFields (QueryFields (ItemTypeOpCode QRExport) fields) = |
318 |
Ok $ fieldsExtractor Export.fieldsMap fields |
319 |
|
320 |
queryFields (QueryFields qkind _) = |
321 |
Bad . GenericError $ "QueryFields '" ++ show qkind ++ "' not supported" |
322 |
|
323 |
-- | Classic query converter. It gets a standard query result on input |
324 |
-- and computes the classic style results. |
325 |
queryCompat :: QueryResult -> ErrorResult [[J.JSValue]] |
326 |
queryCompat (QueryResult fields qrdata) = |
327 |
case map fdefName $ filter ((== QFTUnknown) . fdefKind) fields of |
328 |
[] -> Ok $ map (map (maybe J.JSNull J.showJSON . rentryValue)) qrdata |
329 |
unknown -> Bad $ OpPrereqError ("Unknown output fields selected: " ++ |
330 |
intercalate ", " unknown) ECodeInval |