root / lib / query.py @ 79b2ca83
History | View | Annotate | Download (40.8 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2010, 2011 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Module for query operations
|
23 |
|
24 |
How it works:
|
25 |
|
26 |
- Add field definitions
|
27 |
- See how L{NODE_FIELDS} is built
|
28 |
- Each field gets:
|
29 |
- Query field definition (L{objects.QueryFieldDefinition}, use
|
30 |
L{_MakeField} for creating), containing:
|
31 |
- Name, must be lowercase and match L{FIELD_NAME_RE}
|
32 |
- Title for tables, must not contain whitespace and match
|
33 |
L{TITLE_RE}
|
34 |
- Value data type, e.g. L{constants.QFT_NUMBER}
|
35 |
- Human-readable description, must not end with punctuation or
|
36 |
contain newlines
|
37 |
- Data request type, see e.g. C{NQ_*}
|
38 |
- A retrieval function, see L{Query.__init__} for description
|
39 |
- Pass list of fields through L{_PrepareFieldList} for preparation and
|
40 |
checks
|
41 |
- Instantiate L{Query} with prepared field list definition and selected fields
|
42 |
- Call L{Query.RequestedData} to determine what data to collect/compute
|
43 |
- Call L{Query.Query} or L{Query.OldStyleQuery} with collected data and use
|
44 |
result
|
45 |
- Data container must support iteration using C{__iter__}
|
46 |
- Items are passed to retrieval functions and can have any format
|
47 |
- Call L{Query.GetFields} to get list of definitions for selected fields
|
48 |
|
49 |
@attention: Retrieval functions must be idempotent. They can be called multiple
|
50 |
times, in any order and any number of times. This is important to keep in
|
51 |
mind for implementing filters in the future.
|
52 |
|
53 |
"""
|
54 |
|
55 |
import logging |
56 |
import operator |
57 |
import re |
58 |
|
59 |
from ganeti import constants |
60 |
from ganeti import errors |
61 |
from ganeti import utils |
62 |
from ganeti import compat |
63 |
from ganeti import objects |
64 |
from ganeti import ht |
65 |
|
66 |
from ganeti.constants import (QFT_UNKNOWN, QFT_TEXT, QFT_BOOL, QFT_NUMBER, |
67 |
QFT_UNIT, QFT_TIMESTAMP, QFT_OTHER, |
68 |
RS_NORMAL, RS_UNKNOWN, RS_NODATA, |
69 |
RS_UNAVAIL, RS_OFFLINE) |
70 |
|
71 |
|
72 |
# Constants for requesting data from the caller/data provider. Each property
|
73 |
# collected/computed separately by the data provider should have its own to
|
74 |
# only collect the requested data and not more.
|
75 |
|
76 |
(NQ_CONFIG, |
77 |
NQ_INST, |
78 |
NQ_LIVE, |
79 |
NQ_GROUP, |
80 |
NQ_OOB) = range(1, 6) |
81 |
|
82 |
(IQ_CONFIG, |
83 |
IQ_LIVE, |
84 |
IQ_DISKUSAGE, |
85 |
IQ_CONSOLE) = range(100, 104) |
86 |
|
87 |
(LQ_MODE, |
88 |
LQ_OWNER, |
89 |
LQ_PENDING) = range(10, 13) |
90 |
|
91 |
(GQ_CONFIG, |
92 |
GQ_NODE, |
93 |
GQ_INST) = range(200, 203) |
94 |
|
95 |
|
96 |
FIELD_NAME_RE = re.compile(r"^[a-z0-9/._]+$")
|
97 |
TITLE_RE = re.compile(r"^[^\s]+$")
|
98 |
DOC_RE = re.compile(r"^[A-Z].*[^.,?!]$")
|
99 |
|
100 |
#: Verification function for each field type
|
101 |
_VERIFY_FN = { |
102 |
QFT_UNKNOWN: ht.TNone, |
103 |
QFT_TEXT: ht.TString, |
104 |
QFT_BOOL: ht.TBool, |
105 |
QFT_NUMBER: ht.TInt, |
106 |
QFT_UNIT: ht.TInt, |
107 |
QFT_TIMESTAMP: ht.TOr(ht.TInt, ht.TFloat), |
108 |
QFT_OTHER: lambda _: True, |
109 |
} |
110 |
|
111 |
# Unique objects for special field statuses
|
112 |
_FS_UNKNOWN = object()
|
113 |
_FS_NODATA = object()
|
114 |
_FS_UNAVAIL = object()
|
115 |
_FS_OFFLINE = object()
|
116 |
|
117 |
#: VType to QFT mapping
|
118 |
_VTToQFT = { |
119 |
# TODO: fix validation of empty strings
|
120 |
constants.VTYPE_STRING: QFT_OTHER, # since VTYPE_STRINGs can be empty
|
121 |
constants.VTYPE_MAYBE_STRING: QFT_OTHER, |
122 |
constants.VTYPE_BOOL: QFT_BOOL, |
123 |
constants.VTYPE_SIZE: QFT_UNIT, |
124 |
constants.VTYPE_INT: QFT_NUMBER, |
125 |
} |
126 |
|
127 |
_SERIAL_NO_DOC = "%s object serial number, incremented on each modification"
|
128 |
|
129 |
|
130 |
def _GetUnknownField(ctx, item): # pylint: disable-msg=W0613 |
131 |
"""Gets the contents of an unknown field.
|
132 |
|
133 |
"""
|
134 |
return _FS_UNKNOWN
|
135 |
|
136 |
|
137 |
def _GetQueryFields(fielddefs, selected): |
138 |
"""Calculates the internal list of selected fields.
|
139 |
|
140 |
Unknown fields are returned as L{constants.QFT_UNKNOWN}.
|
141 |
|
142 |
@type fielddefs: dict
|
143 |
@param fielddefs: Field definitions
|
144 |
@type selected: list of strings
|
145 |
@param selected: List of selected fields
|
146 |
|
147 |
"""
|
148 |
result = [] |
149 |
|
150 |
for name in selected: |
151 |
try:
|
152 |
fdef = fielddefs[name] |
153 |
except KeyError: |
154 |
fdef = (_MakeField(name, name, QFT_UNKNOWN, "Unknown field '%s'" % name),
|
155 |
None, _GetUnknownField)
|
156 |
|
157 |
assert len(fdef) == 3 |
158 |
|
159 |
result.append(fdef) |
160 |
|
161 |
return result
|
162 |
|
163 |
|
164 |
def GetAllFields(fielddefs): |
165 |
"""Extract L{objects.QueryFieldDefinition} from field definitions.
|
166 |
|
167 |
@rtype: list of L{objects.QueryFieldDefinition}
|
168 |
|
169 |
"""
|
170 |
return [fdef for (fdef, _, _) in fielddefs] |
171 |
|
172 |
|
173 |
class Query: |
174 |
def __init__(self, fieldlist, selected): |
175 |
"""Initializes this class.
|
176 |
|
177 |
The field definition is a dictionary with the field's name as a key and a
|
178 |
tuple containing, in order, the field definition object
|
179 |
(L{objects.QueryFieldDefinition}, the data kind to help calling code
|
180 |
collect data and a retrieval function. The retrieval function is called
|
181 |
with two parameters, in order, the data container and the item in container
|
182 |
(see L{Query.Query}).
|
183 |
|
184 |
Users of this class can call L{RequestedData} before preparing the data
|
185 |
container to determine what data is needed.
|
186 |
|
187 |
@type fieldlist: dictionary
|
188 |
@param fieldlist: Field definitions
|
189 |
@type selected: list of strings
|
190 |
@param selected: List of selected fields
|
191 |
|
192 |
"""
|
193 |
self._fields = _GetQueryFields(fieldlist, selected)
|
194 |
|
195 |
def RequestedData(self): |
196 |
"""Gets requested kinds of data.
|
197 |
|
198 |
@rtype: frozenset
|
199 |
|
200 |
"""
|
201 |
return frozenset(datakind |
202 |
for (_, datakind, _) in self._fields |
203 |
if datakind is not None) |
204 |
|
205 |
def GetFields(self): |
206 |
"""Returns the list of fields for this query.
|
207 |
|
208 |
Includes unknown fields.
|
209 |
|
210 |
@rtype: List of L{objects.QueryFieldDefinition}
|
211 |
|
212 |
"""
|
213 |
return GetAllFields(self._fields) |
214 |
|
215 |
def Query(self, ctx): |
216 |
"""Execute a query.
|
217 |
|
218 |
@param ctx: Data container passed to field retrieval functions, must
|
219 |
support iteration using C{__iter__}
|
220 |
|
221 |
"""
|
222 |
result = [[_ProcessResult(fn(ctx, item)) for (_, _, fn) in self._fields] |
223 |
for item in ctx] |
224 |
|
225 |
# Verify result
|
226 |
if __debug__:
|
227 |
for row in result: |
228 |
_VerifyResultRow(self._fields, row)
|
229 |
|
230 |
return result
|
231 |
|
232 |
def OldStyleQuery(self, ctx): |
233 |
"""Query with "old" query result format.
|
234 |
|
235 |
See L{Query.Query} for arguments.
|
236 |
|
237 |
"""
|
238 |
unknown = set(fdef.name
|
239 |
for (fdef, _, _) in self._fields if fdef.kind == QFT_UNKNOWN) |
240 |
if unknown:
|
241 |
raise errors.OpPrereqError("Unknown output fields selected: %s" % |
242 |
(utils.CommaJoin(unknown), ), |
243 |
errors.ECODE_INVAL) |
244 |
|
245 |
return [[value for (_, value) in row] |
246 |
for row in self.Query(ctx)] |
247 |
|
248 |
|
249 |
def _ProcessResult(value): |
250 |
"""Converts result values into externally-visible ones.
|
251 |
|
252 |
"""
|
253 |
if value is _FS_UNKNOWN: |
254 |
return (RS_UNKNOWN, None) |
255 |
elif value is _FS_NODATA: |
256 |
return (RS_NODATA, None) |
257 |
elif value is _FS_UNAVAIL: |
258 |
return (RS_UNAVAIL, None) |
259 |
elif value is _FS_OFFLINE: |
260 |
return (RS_OFFLINE, None) |
261 |
else:
|
262 |
return (RS_NORMAL, value)
|
263 |
|
264 |
|
265 |
def _VerifyResultRow(fields, row): |
266 |
"""Verifies the contents of a query result row.
|
267 |
|
268 |
@type fields: list
|
269 |
@param fields: Field definitions for result
|
270 |
@type row: list of tuples
|
271 |
@param row: Row data
|
272 |
|
273 |
"""
|
274 |
assert len(row) == len(fields) |
275 |
errs = [] |
276 |
for ((status, value), (fdef, _, _)) in zip(row, fields): |
277 |
if status == RS_NORMAL:
|
278 |
if not _VERIFY_FN[fdef.kind](value): |
279 |
errs.append("normal field %s fails validation (value is %s)" %
|
280 |
(fdef.name, value)) |
281 |
elif value is not None: |
282 |
errs.append("abnormal field %s has a non-None value" % fdef.name)
|
283 |
assert not errs, ("Failed validation: %s in row %s" % |
284 |
(utils.CommaJoin(errors), row)) |
285 |
|
286 |
|
287 |
def _PrepareFieldList(fields, aliases): |
288 |
"""Prepares field list for use by L{Query}.
|
289 |
|
290 |
Converts the list to a dictionary and does some verification.
|
291 |
|
292 |
@type fields: list of tuples; (L{objects.QueryFieldDefinition}, data
|
293 |
kind, retrieval function)
|
294 |
@param fields: List of fields, see L{Query.__init__} for a better
|
295 |
description
|
296 |
@type aliases: list of tuples; (alias, target)
|
297 |
@param aliases: list of tuples containing aliases; for each
|
298 |
alias/target pair, a duplicate will be created in the field list
|
299 |
@rtype: dict
|
300 |
@return: Field dictionary for L{Query}
|
301 |
|
302 |
"""
|
303 |
if __debug__:
|
304 |
duplicates = utils.FindDuplicates(fdef.title.lower() |
305 |
for (fdef, _, _) in fields) |
306 |
assert not duplicates, "Duplicate title(s) found: %r" % duplicates |
307 |
|
308 |
result = {} |
309 |
|
310 |
for field in fields: |
311 |
(fdef, _, fn) = field |
312 |
|
313 |
assert fdef.name and fdef.title, "Name and title are required" |
314 |
assert FIELD_NAME_RE.match(fdef.name)
|
315 |
assert TITLE_RE.match(fdef.title)
|
316 |
assert (DOC_RE.match(fdef.doc) and len(fdef.doc.splitlines()) == 1 and |
317 |
fdef.doc.strip() == fdef.doc), \ |
318 |
"Invalid description for field '%s'" % fdef.name
|
319 |
assert callable(fn) |
320 |
assert fdef.name not in result, \ |
321 |
"Duplicate field name '%s' found" % fdef.name
|
322 |
|
323 |
result[fdef.name] = field |
324 |
|
325 |
for alias, target in aliases: |
326 |
assert alias not in result, "Alias %s overrides an existing field" % alias |
327 |
assert target in result, "Missing target %s for alias %s" % (target, alias) |
328 |
(fdef, k, fn) = result[target] |
329 |
fdef = fdef.Copy() |
330 |
fdef.name = alias |
331 |
result[alias] = (fdef, k, fn) |
332 |
|
333 |
assert len(result) == len(fields) + len(aliases) |
334 |
assert compat.all(name == fdef.name
|
335 |
for (name, (fdef, _, _)) in result.items()) |
336 |
|
337 |
return result
|
338 |
|
339 |
|
340 |
def GetQueryResponse(query, ctx): |
341 |
"""Prepares the response for a query.
|
342 |
|
343 |
@type query: L{Query}
|
344 |
@param ctx: Data container, see L{Query.Query}
|
345 |
|
346 |
"""
|
347 |
return objects.QueryResponse(data=query.Query(ctx),
|
348 |
fields=query.GetFields()).ToDict() |
349 |
|
350 |
|
351 |
def QueryFields(fielddefs, selected): |
352 |
"""Returns list of available fields.
|
353 |
|
354 |
@type fielddefs: dict
|
355 |
@param fielddefs: Field definitions
|
356 |
@type selected: list of strings
|
357 |
@param selected: List of selected fields
|
358 |
@return: List of L{objects.QueryFieldDefinition}
|
359 |
|
360 |
"""
|
361 |
if selected is None: |
362 |
# Client requests all fields, sort by name
|
363 |
fdefs = utils.NiceSort(GetAllFields(fielddefs.values()), |
364 |
key=operator.attrgetter("name"))
|
365 |
else:
|
366 |
# Keep order as requested by client
|
367 |
fdefs = Query(fielddefs, selected).GetFields() |
368 |
|
369 |
return objects.QueryFieldsResponse(fields=fdefs).ToDict()
|
370 |
|
371 |
|
372 |
def _MakeField(name, title, kind, doc): |
373 |
"""Wrapper for creating L{objects.QueryFieldDefinition} instances.
|
374 |
|
375 |
@param name: Field name as a regular expression
|
376 |
@param title: Human-readable title
|
377 |
@param kind: Field type
|
378 |
@param doc: Human-readable description
|
379 |
|
380 |
"""
|
381 |
return objects.QueryFieldDefinition(name=name, title=title, kind=kind,
|
382 |
doc=doc) |
383 |
|
384 |
|
385 |
def _GetNodeRole(node, master_name): |
386 |
"""Determine node role.
|
387 |
|
388 |
@type node: L{objects.Node}
|
389 |
@param node: Node object
|
390 |
@type master_name: string
|
391 |
@param master_name: Master node name
|
392 |
|
393 |
"""
|
394 |
if node.name == master_name:
|
395 |
return constants.NR_MASTER
|
396 |
elif node.master_candidate:
|
397 |
return constants.NR_MCANDIDATE
|
398 |
elif node.drained:
|
399 |
return constants.NR_DRAINED
|
400 |
elif node.offline:
|
401 |
return constants.NR_OFFLINE
|
402 |
else:
|
403 |
return constants.NR_REGULAR
|
404 |
|
405 |
|
406 |
def _GetItemAttr(attr): |
407 |
"""Returns a field function to return an attribute of the item.
|
408 |
|
409 |
@param attr: Attribute name
|
410 |
|
411 |
"""
|
412 |
getter = operator.attrgetter(attr) |
413 |
return lambda _, item: getter(item) |
414 |
|
415 |
|
416 |
def _GetItemTimestamp(getter): |
417 |
"""Returns function for getting timestamp of item.
|
418 |
|
419 |
@type getter: callable
|
420 |
@param getter: Function to retrieve timestamp attribute
|
421 |
|
422 |
"""
|
423 |
def fn(_, item): |
424 |
"""Returns a timestamp of item.
|
425 |
|
426 |
"""
|
427 |
timestamp = getter(item) |
428 |
if timestamp is None: |
429 |
# Old configs might not have all timestamps
|
430 |
return _FS_UNAVAIL
|
431 |
else:
|
432 |
return timestamp
|
433 |
|
434 |
return fn
|
435 |
|
436 |
|
437 |
def _GetItemTimestampFields(datatype): |
438 |
"""Returns common timestamp fields.
|
439 |
|
440 |
@param datatype: Field data type for use by L{Query.RequestedData}
|
441 |
|
442 |
"""
|
443 |
return [
|
444 |
(_MakeField("ctime", "CTime", QFT_TIMESTAMP, "Creation timestamp"), |
445 |
datatype, _GetItemTimestamp(operator.attrgetter("ctime"))),
|
446 |
(_MakeField("mtime", "MTime", QFT_TIMESTAMP, "Modification timestamp"), |
447 |
datatype, _GetItemTimestamp(operator.attrgetter("mtime"))),
|
448 |
] |
449 |
|
450 |
|
451 |
class NodeQueryData: |
452 |
"""Data container for node data queries.
|
453 |
|
454 |
"""
|
455 |
def __init__(self, nodes, live_data, master_name, node_to_primary, |
456 |
node_to_secondary, groups, oob_support, cluster): |
457 |
"""Initializes this class.
|
458 |
|
459 |
"""
|
460 |
self.nodes = nodes
|
461 |
self.live_data = live_data
|
462 |
self.master_name = master_name
|
463 |
self.node_to_primary = node_to_primary
|
464 |
self.node_to_secondary = node_to_secondary
|
465 |
self.groups = groups
|
466 |
self.oob_support = oob_support
|
467 |
self.cluster = cluster
|
468 |
|
469 |
# Used for individual rows
|
470 |
self.curlive_data = None |
471 |
|
472 |
def __iter__(self): |
473 |
"""Iterate over all nodes.
|
474 |
|
475 |
This function has side-effects and only one instance of the resulting
|
476 |
generator should be used at a time.
|
477 |
|
478 |
"""
|
479 |
for node in self.nodes: |
480 |
if self.live_data: |
481 |
self.curlive_data = self.live_data.get(node.name, None) |
482 |
else:
|
483 |
self.curlive_data = None |
484 |
yield node
|
485 |
|
486 |
|
487 |
#: Fields that are direct attributes of an L{objects.Node} object
|
488 |
_NODE_SIMPLE_FIELDS = { |
489 |
"drained": ("Drained", QFT_BOOL, "Whether node is drained"), |
490 |
"master_candidate": ("MasterC", QFT_BOOL, |
491 |
"Whether node is a master candidate"),
|
492 |
"master_capable": ("MasterCapable", QFT_BOOL, |
493 |
"Whether node can become a master candidate"),
|
494 |
"name": ("Node", QFT_TEXT, "Node name"), |
495 |
"offline": ("Offline", QFT_BOOL, "Whether node is marked offline"), |
496 |
"serial_no": ("SerialNo", QFT_NUMBER, _SERIAL_NO_DOC % "Node"), |
497 |
"uuid": ("UUID", QFT_TEXT, "Node UUID"), |
498 |
"vm_capable": ("VMCapable", QFT_BOOL, "Whether node can host instances"), |
499 |
} |
500 |
|
501 |
|
502 |
#: Fields requiring talking to the node
|
503 |
# Note that none of these are available for non-vm_capable nodes
|
504 |
_NODE_LIVE_FIELDS = { |
505 |
"bootid": ("BootID", QFT_TEXT, "bootid", |
506 |
"Random UUID renewed for each system reboot, can be used"
|
507 |
" for detecting reboots by tracking changes"),
|
508 |
"cnodes": ("CNodes", QFT_NUMBER, "cpu_nodes", |
509 |
"Number of NUMA domains on node (if exported by hypervisor)"),
|
510 |
"csockets": ("CSockets", QFT_NUMBER, "cpu_sockets", |
511 |
"Number of physical CPU sockets (if exported by hypervisor)"),
|
512 |
"ctotal": ("CTotal", QFT_NUMBER, "cpu_total", "Number of logical processors"), |
513 |
"dfree": ("DFree", QFT_UNIT, "vg_free", |
514 |
"Available disk space in volume group"),
|
515 |
"dtotal": ("DTotal", QFT_UNIT, "vg_size", |
516 |
"Total disk space in volume group used for instance disk"
|
517 |
" allocation"),
|
518 |
"mfree": ("MFree", QFT_UNIT, "memory_free", |
519 |
"Memory available for instance allocations"),
|
520 |
"mnode": ("MNode", QFT_UNIT, "memory_dom0", |
521 |
"Amount of memory used by node (dom0 for Xen)"),
|
522 |
"mtotal": ("MTotal", QFT_UNIT, "memory_total", |
523 |
"Total amount of memory of physical machine"),
|
524 |
} |
525 |
|
526 |
|
527 |
def _GetGroup(cb): |
528 |
"""Build function for calling another function with an node group.
|
529 |
|
530 |
@param cb: The callback to be called with the nodegroup
|
531 |
|
532 |
"""
|
533 |
def fn(ctx, node): |
534 |
"""Get group data for a node.
|
535 |
|
536 |
@type ctx: L{NodeQueryData}
|
537 |
@type inst: L{objects.Node}
|
538 |
@param inst: Node object
|
539 |
|
540 |
"""
|
541 |
ng = ctx.groups.get(node.group, None)
|
542 |
if ng is None: |
543 |
# Nodes always have a group, or the configuration is corrupt
|
544 |
return _FS_UNAVAIL
|
545 |
|
546 |
return cb(ctx, node, ng)
|
547 |
|
548 |
return fn
|
549 |
|
550 |
|
551 |
def _GetNodeGroup(ctx, node, ng): # pylint: disable-msg=W0613 |
552 |
"""Returns the name of a node's group.
|
553 |
|
554 |
@type ctx: L{NodeQueryData}
|
555 |
@type node: L{objects.Node}
|
556 |
@param node: Node object
|
557 |
@type ng: L{objects.NodeGroup}
|
558 |
@param ng: The node group this node belongs to
|
559 |
|
560 |
"""
|
561 |
return ng.name
|
562 |
|
563 |
|
564 |
def _GetNodePower(ctx, node): |
565 |
"""Returns the node powered state
|
566 |
|
567 |
@type ctx: L{NodeQueryData}
|
568 |
@type node: L{objects.Node}
|
569 |
@param node: Node object
|
570 |
|
571 |
"""
|
572 |
if ctx.oob_support[node.name]:
|
573 |
return node.powered
|
574 |
|
575 |
return _FS_UNAVAIL
|
576 |
|
577 |
|
578 |
def _GetNdParams(ctx, node, ng): |
579 |
"""Returns the ndparams for this node.
|
580 |
|
581 |
@type ctx: L{NodeQueryData}
|
582 |
@type node: L{objects.Node}
|
583 |
@param node: Node object
|
584 |
@type ng: L{objects.NodeGroup}
|
585 |
@param ng: The node group this node belongs to
|
586 |
|
587 |
"""
|
588 |
return ctx.cluster.SimpleFillND(ng.FillND(node))
|
589 |
|
590 |
|
591 |
def _GetLiveNodeField(field, kind, ctx, node): |
592 |
"""Gets the value of a "live" field from L{NodeQueryData}.
|
593 |
|
594 |
@param field: Live field name
|
595 |
@param kind: Data kind, one of L{constants.QFT_ALL}
|
596 |
@type ctx: L{NodeQueryData}
|
597 |
@type node: L{objects.Node}
|
598 |
@param node: Node object
|
599 |
|
600 |
"""
|
601 |
if node.offline:
|
602 |
return _FS_OFFLINE
|
603 |
|
604 |
if not node.vm_capable: |
605 |
return _FS_UNAVAIL
|
606 |
|
607 |
if not ctx.curlive_data: |
608 |
return _FS_NODATA
|
609 |
|
610 |
try:
|
611 |
value = ctx.curlive_data[field] |
612 |
except KeyError: |
613 |
return _FS_UNAVAIL
|
614 |
|
615 |
if kind == QFT_TEXT:
|
616 |
return value
|
617 |
|
618 |
assert kind in (QFT_NUMBER, QFT_UNIT) |
619 |
|
620 |
# Try to convert into number
|
621 |
try:
|
622 |
return int(value) |
623 |
except (ValueError, TypeError): |
624 |
logging.exception("Failed to convert node field '%s' (value %r) to int",
|
625 |
value, field) |
626 |
return _FS_UNAVAIL
|
627 |
|
628 |
|
629 |
def _BuildNodeFields(): |
630 |
"""Builds list of fields for node queries.
|
631 |
|
632 |
"""
|
633 |
fields = [ |
634 |
(_MakeField("pip", "PrimaryIP", QFT_TEXT, "Primary IP address"), |
635 |
NQ_CONFIG, _GetItemAttr("primary_ip")),
|
636 |
(_MakeField("sip", "SecondaryIP", QFT_TEXT, "Secondary IP address"), |
637 |
NQ_CONFIG, _GetItemAttr("secondary_ip")),
|
638 |
(_MakeField("tags", "Tags", QFT_OTHER, "Tags"), NQ_CONFIG, |
639 |
lambda ctx, node: list(node.GetTags())), |
640 |
(_MakeField("master", "IsMaster", QFT_BOOL, "Whether node is master"), |
641 |
NQ_CONFIG, lambda ctx, node: node.name == ctx.master_name),
|
642 |
(_MakeField("group", "Group", QFT_TEXT, "Node group"), NQ_GROUP, |
643 |
_GetGroup(_GetNodeGroup)), |
644 |
(_MakeField("group.uuid", "GroupUUID", QFT_TEXT, "UUID of node group"), |
645 |
NQ_CONFIG, _GetItemAttr("group")),
|
646 |
(_MakeField("powered", "Powered", QFT_BOOL, |
647 |
"Whether node is thought to be powered on"),
|
648 |
NQ_OOB, _GetNodePower), |
649 |
(_MakeField("ndparams", "NodeParameters", QFT_OTHER, |
650 |
"Merged node parameters"),
|
651 |
NQ_GROUP, _GetGroup(_GetNdParams)), |
652 |
(_MakeField("custom_ndparams", "CustomNodeParameters", QFT_OTHER, |
653 |
"Custom node parameters"),
|
654 |
NQ_GROUP, _GetItemAttr("ndparams")),
|
655 |
] |
656 |
|
657 |
# Node role
|
658 |
role_values = (constants.NR_MASTER, constants.NR_MCANDIDATE, |
659 |
constants.NR_REGULAR, constants.NR_DRAINED, |
660 |
constants.NR_OFFLINE) |
661 |
role_doc = ("Node role; \"%s\" for master, \"%s\" for master candidate,"
|
662 |
" \"%s\" for regular, \"%s\" for a drained, \"%s\" for offline" %
|
663 |
role_values) |
664 |
fields.append((_MakeField("role", "Role", QFT_TEXT, role_doc), NQ_CONFIG, |
665 |
lambda ctx, node: _GetNodeRole(node, ctx.master_name)))
|
666 |
assert set(role_values) == constants.NR_ALL |
667 |
|
668 |
def _GetLength(getter): |
669 |
return lambda ctx, node: len(getter(ctx)[node.name]) |
670 |
|
671 |
def _GetList(getter): |
672 |
return lambda ctx, node: list(getter(ctx)[node.name]) |
673 |
|
674 |
# Add fields operating on instance lists
|
675 |
for prefix, titleprefix, docword, getter in \ |
676 |
[("p", "Pri", "primary", operator.attrgetter("node_to_primary")), |
677 |
("s", "Sec", "secondary", operator.attrgetter("node_to_secondary"))]: |
678 |
fields.extend([ |
679 |
(_MakeField("%sinst_cnt" % prefix, "%sinst" % prefix.upper(), QFT_NUMBER, |
680 |
"Number of instances with this node as %s" % docword),
|
681 |
NQ_INST, _GetLength(getter)), |
682 |
(_MakeField("%sinst_list" % prefix, "%sInstances" % titleprefix, |
683 |
QFT_OTHER, |
684 |
"List of instances with this node as %s" % docword),
|
685 |
NQ_INST, _GetList(getter)), |
686 |
]) |
687 |
|
688 |
# Add simple fields
|
689 |
fields.extend([(_MakeField(name, title, kind, doc), NQ_CONFIG, |
690 |
_GetItemAttr(name)) |
691 |
for (name, (title, kind, doc)) in _NODE_SIMPLE_FIELDS.items()]) |
692 |
|
693 |
# Add fields requiring live data
|
694 |
fields.extend([ |
695 |
(_MakeField(name, title, kind, doc), NQ_LIVE, |
696 |
compat.partial(_GetLiveNodeField, nfield, kind)) |
697 |
for (name, (title, kind, nfield, doc)) in _NODE_LIVE_FIELDS.items() |
698 |
]) |
699 |
|
700 |
# Add timestamps
|
701 |
fields.extend(_GetItemTimestampFields(NQ_CONFIG)) |
702 |
|
703 |
return _PrepareFieldList(fields, [])
|
704 |
|
705 |
|
706 |
class InstanceQueryData: |
707 |
"""Data container for instance data queries.
|
708 |
|
709 |
"""
|
710 |
def __init__(self, instances, cluster, disk_usage, offline_nodes, bad_nodes, |
711 |
live_data, wrongnode_inst, console): |
712 |
"""Initializes this class.
|
713 |
|
714 |
@param instances: List of instance objects
|
715 |
@param cluster: Cluster object
|
716 |
@type disk_usage: dict; instance name as key
|
717 |
@param disk_usage: Per-instance disk usage
|
718 |
@type offline_nodes: list of strings
|
719 |
@param offline_nodes: List of offline nodes
|
720 |
@type bad_nodes: list of strings
|
721 |
@param bad_nodes: List of faulty nodes
|
722 |
@type live_data: dict; instance name as key
|
723 |
@param live_data: Per-instance live data
|
724 |
@type wrongnode_inst: set
|
725 |
@param wrongnode_inst: Set of instances running on wrong node(s)
|
726 |
@type console: dict; instance name as key
|
727 |
@param console: Per-instance console information
|
728 |
|
729 |
"""
|
730 |
assert len(set(bad_nodes) & set(offline_nodes)) == len(offline_nodes), \ |
731 |
"Offline nodes not included in bad nodes"
|
732 |
assert not (set(live_data.keys()) & set(bad_nodes)), \ |
733 |
"Found live data for bad or offline nodes"
|
734 |
|
735 |
self.instances = instances
|
736 |
self.cluster = cluster
|
737 |
self.disk_usage = disk_usage
|
738 |
self.offline_nodes = offline_nodes
|
739 |
self.bad_nodes = bad_nodes
|
740 |
self.live_data = live_data
|
741 |
self.wrongnode_inst = wrongnode_inst
|
742 |
self.console = console
|
743 |
|
744 |
# Used for individual rows
|
745 |
self.inst_hvparams = None |
746 |
self.inst_beparams = None |
747 |
self.inst_nicparams = None |
748 |
|
749 |
def __iter__(self): |
750 |
"""Iterate over all instances.
|
751 |
|
752 |
This function has side-effects and only one instance of the resulting
|
753 |
generator should be used at a time.
|
754 |
|
755 |
"""
|
756 |
for inst in self.instances: |
757 |
self.inst_hvparams = self.cluster.FillHV(inst, skip_globals=True) |
758 |
self.inst_beparams = self.cluster.FillBE(inst) |
759 |
self.inst_nicparams = [self.cluster.SimpleFillNIC(nic.nicparams) |
760 |
for nic in inst.nics] |
761 |
|
762 |
yield inst
|
763 |
|
764 |
|
765 |
def _GetInstOperState(ctx, inst): |
766 |
"""Get instance's operational status.
|
767 |
|
768 |
@type ctx: L{InstanceQueryData}
|
769 |
@type inst: L{objects.Instance}
|
770 |
@param inst: Instance object
|
771 |
|
772 |
"""
|
773 |
# Can't use RS_OFFLINE here as it would describe the instance to
|
774 |
# be offline when we actually don't know due to missing data
|
775 |
if inst.primary_node in ctx.bad_nodes: |
776 |
return _FS_NODATA
|
777 |
else:
|
778 |
return bool(ctx.live_data.get(inst.name)) |
779 |
|
780 |
|
781 |
def _GetInstLiveData(name): |
782 |
"""Build function for retrieving live data.
|
783 |
|
784 |
@type name: string
|
785 |
@param name: Live data field name
|
786 |
|
787 |
"""
|
788 |
def fn(ctx, inst): |
789 |
"""Get live data for an instance.
|
790 |
|
791 |
@type ctx: L{InstanceQueryData}
|
792 |
@type inst: L{objects.Instance}
|
793 |
@param inst: Instance object
|
794 |
|
795 |
"""
|
796 |
if (inst.primary_node in ctx.bad_nodes or |
797 |
inst.primary_node in ctx.offline_nodes):
|
798 |
# Can't use RS_OFFLINE here as it would describe the instance to be
|
799 |
# offline when we actually don't know due to missing data
|
800 |
return _FS_NODATA
|
801 |
|
802 |
if inst.name in ctx.live_data: |
803 |
data = ctx.live_data[inst.name] |
804 |
if name in data: |
805 |
return data[name]
|
806 |
|
807 |
return _FS_UNAVAIL
|
808 |
|
809 |
return fn
|
810 |
|
811 |
|
812 |
def _GetInstStatus(ctx, inst): |
813 |
"""Get instance status.
|
814 |
|
815 |
@type ctx: L{InstanceQueryData}
|
816 |
@type inst: L{objects.Instance}
|
817 |
@param inst: Instance object
|
818 |
|
819 |
"""
|
820 |
if inst.primary_node in ctx.offline_nodes: |
821 |
return constants.INSTST_NODEOFFLINE
|
822 |
|
823 |
if inst.primary_node in ctx.bad_nodes: |
824 |
return constants.INSTST_NODEDOWN
|
825 |
|
826 |
if bool(ctx.live_data.get(inst.name)): |
827 |
if inst.name in ctx.wrongnode_inst: |
828 |
return constants.INSTST_WRONGNODE
|
829 |
elif inst.admin_up:
|
830 |
return constants.INSTST_RUNNING
|
831 |
else:
|
832 |
return constants.INSTST_ERRORUP
|
833 |
|
834 |
if inst.admin_up:
|
835 |
return constants.INSTST_ERRORDOWN
|
836 |
|
837 |
return constants.INSTST_ADMINDOWN
|
838 |
|
839 |
|
840 |
def _GetInstDiskSize(index): |
841 |
"""Build function for retrieving disk size.
|
842 |
|
843 |
@type index: int
|
844 |
@param index: Disk index
|
845 |
|
846 |
"""
|
847 |
def fn(_, inst): |
848 |
"""Get size of a disk.
|
849 |
|
850 |
@type inst: L{objects.Instance}
|
851 |
@param inst: Instance object
|
852 |
|
853 |
"""
|
854 |
try:
|
855 |
return inst.disks[index].size
|
856 |
except IndexError: |
857 |
return _FS_UNAVAIL
|
858 |
|
859 |
return fn
|
860 |
|
861 |
|
862 |
def _GetInstNic(index, cb): |
863 |
"""Build function for calling another function with an instance NIC.
|
864 |
|
865 |
@type index: int
|
866 |
@param index: NIC index
|
867 |
@type cb: callable
|
868 |
@param cb: Callback
|
869 |
|
870 |
"""
|
871 |
def fn(ctx, inst): |
872 |
"""Call helper function with instance NIC.
|
873 |
|
874 |
@type ctx: L{InstanceQueryData}
|
875 |
@type inst: L{objects.Instance}
|
876 |
@param inst: Instance object
|
877 |
|
878 |
"""
|
879 |
try:
|
880 |
nic = inst.nics[index] |
881 |
except IndexError: |
882 |
return _FS_UNAVAIL
|
883 |
|
884 |
return cb(ctx, index, nic)
|
885 |
|
886 |
return fn
|
887 |
|
888 |
|
889 |
def _GetInstNicIp(ctx, _, nic): # pylint: disable-msg=W0613 |
890 |
"""Get a NIC's IP address.
|
891 |
|
892 |
@type ctx: L{InstanceQueryData}
|
893 |
@type nic: L{objects.NIC}
|
894 |
@param nic: NIC object
|
895 |
|
896 |
"""
|
897 |
if nic.ip is None: |
898 |
return _FS_UNAVAIL
|
899 |
else:
|
900 |
return nic.ip
|
901 |
|
902 |
|
903 |
def _GetInstNicBridge(ctx, index, _): |
904 |
"""Get a NIC's bridge.
|
905 |
|
906 |
@type ctx: L{InstanceQueryData}
|
907 |
@type index: int
|
908 |
@param index: NIC index
|
909 |
|
910 |
"""
|
911 |
assert len(ctx.inst_nicparams) >= index |
912 |
|
913 |
nicparams = ctx.inst_nicparams[index] |
914 |
|
915 |
if nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
|
916 |
return nicparams[constants.NIC_LINK]
|
917 |
else:
|
918 |
return _FS_UNAVAIL
|
919 |
|
920 |
|
921 |
def _GetInstAllNicBridges(ctx, inst): |
922 |
"""Get all network bridges for an instance.
|
923 |
|
924 |
@type ctx: L{InstanceQueryData}
|
925 |
@type inst: L{objects.Instance}
|
926 |
@param inst: Instance object
|
927 |
|
928 |
"""
|
929 |
assert len(ctx.inst_nicparams) == len(inst.nics) |
930 |
|
931 |
result = [] |
932 |
|
933 |
for nicp in ctx.inst_nicparams: |
934 |
if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
|
935 |
result.append(nicp[constants.NIC_LINK]) |
936 |
else:
|
937 |
result.append(None)
|
938 |
|
939 |
assert len(result) == len(inst.nics) |
940 |
|
941 |
return result
|
942 |
|
943 |
|
944 |
def _GetInstNicParam(name): |
945 |
"""Build function for retrieving a NIC parameter.
|
946 |
|
947 |
@type name: string
|
948 |
@param name: Parameter name
|
949 |
|
950 |
"""
|
951 |
def fn(ctx, index, _): |
952 |
"""Get a NIC's bridge.
|
953 |
|
954 |
@type ctx: L{InstanceQueryData}
|
955 |
@type inst: L{objects.Instance}
|
956 |
@param inst: Instance object
|
957 |
@type nic: L{objects.NIC}
|
958 |
@param nic: NIC object
|
959 |
|
960 |
"""
|
961 |
assert len(ctx.inst_nicparams) >= index |
962 |
return ctx.inst_nicparams[index][name]
|
963 |
|
964 |
return fn
|
965 |
|
966 |
|
967 |
def _GetInstanceNetworkFields(): |
968 |
"""Get instance fields involving network interfaces.
|
969 |
|
970 |
@return: Tuple containing list of field definitions used as input for
|
971 |
L{_PrepareFieldList} and a list of aliases
|
972 |
|
973 |
"""
|
974 |
nic_mac_fn = lambda ctx, _, nic: nic.mac
|
975 |
nic_mode_fn = _GetInstNicParam(constants.NIC_MODE) |
976 |
nic_link_fn = _GetInstNicParam(constants.NIC_LINK) |
977 |
|
978 |
fields = [ |
979 |
# All NICs
|
980 |
(_MakeField("nic.count", "NICs", QFT_NUMBER, |
981 |
"Number of network interfaces"),
|
982 |
IQ_CONFIG, lambda ctx, inst: len(inst.nics)), |
983 |
(_MakeField("nic.macs", "NIC_MACs", QFT_OTHER, |
984 |
"List containing each network interface's MAC address"),
|
985 |
IQ_CONFIG, lambda ctx, inst: [nic.mac for nic in inst.nics]), |
986 |
(_MakeField("nic.ips", "NIC_IPs", QFT_OTHER, |
987 |
"List containing each network interface's IP address"),
|
988 |
IQ_CONFIG, lambda ctx, inst: [nic.ip for nic in inst.nics]), |
989 |
(_MakeField("nic.modes", "NIC_modes", QFT_OTHER, |
990 |
"List containing each network interface's mode"), IQ_CONFIG,
|
991 |
lambda ctx, inst: [nicp[constants.NIC_MODE]
|
992 |
for nicp in ctx.inst_nicparams]), |
993 |
(_MakeField("nic.links", "NIC_links", QFT_OTHER, |
994 |
"List containing each network interface's link"), IQ_CONFIG,
|
995 |
lambda ctx, inst: [nicp[constants.NIC_LINK]
|
996 |
for nicp in ctx.inst_nicparams]), |
997 |
(_MakeField("nic.bridges", "NIC_bridges", QFT_OTHER, |
998 |
"List containing each network interface's bridge"), IQ_CONFIG,
|
999 |
_GetInstAllNicBridges), |
1000 |
] |
1001 |
|
1002 |
# NICs by number
|
1003 |
for i in range(constants.MAX_NICS): |
1004 |
numtext = utils.FormatOrdinal(i + 1)
|
1005 |
fields.extend([ |
1006 |
(_MakeField("nic.ip/%s" % i, "NicIP/%s" % i, QFT_TEXT, |
1007 |
"IP address of %s network interface" % numtext),
|
1008 |
IQ_CONFIG, _GetInstNic(i, _GetInstNicIp)), |
1009 |
(_MakeField("nic.mac/%s" % i, "NicMAC/%s" % i, QFT_TEXT, |
1010 |
"MAC address of %s network interface" % numtext),
|
1011 |
IQ_CONFIG, _GetInstNic(i, nic_mac_fn)), |
1012 |
(_MakeField("nic.mode/%s" % i, "NicMode/%s" % i, QFT_TEXT, |
1013 |
"Mode of %s network interface" % numtext),
|
1014 |
IQ_CONFIG, _GetInstNic(i, nic_mode_fn)), |
1015 |
(_MakeField("nic.link/%s" % i, "NicLink/%s" % i, QFT_TEXT, |
1016 |
"Link of %s network interface" % numtext),
|
1017 |
IQ_CONFIG, _GetInstNic(i, nic_link_fn)), |
1018 |
(_MakeField("nic.bridge/%s" % i, "NicBridge/%s" % i, QFT_TEXT, |
1019 |
"Bridge of %s network interface" % numtext),
|
1020 |
IQ_CONFIG, _GetInstNic(i, _GetInstNicBridge)), |
1021 |
]) |
1022 |
|
1023 |
aliases = [ |
1024 |
# Legacy fields for first NIC
|
1025 |
("ip", "nic.ip/0"), |
1026 |
("mac", "nic.mac/0"), |
1027 |
("bridge", "nic.bridge/0"), |
1028 |
("nic_mode", "nic.mode/0"), |
1029 |
("nic_link", "nic.link/0"), |
1030 |
] |
1031 |
|
1032 |
return (fields, aliases)
|
1033 |
|
1034 |
|
1035 |
def _GetInstDiskUsage(ctx, inst): |
1036 |
"""Get disk usage for an instance.
|
1037 |
|
1038 |
@type ctx: L{InstanceQueryData}
|
1039 |
@type inst: L{objects.Instance}
|
1040 |
@param inst: Instance object
|
1041 |
|
1042 |
"""
|
1043 |
usage = ctx.disk_usage[inst.name] |
1044 |
|
1045 |
if usage is None: |
1046 |
usage = 0
|
1047 |
|
1048 |
return usage
|
1049 |
|
1050 |
|
1051 |
def _GetInstanceConsole(ctx, inst): |
1052 |
"""Get console information for instance.
|
1053 |
|
1054 |
@type ctx: L{InstanceQueryData}
|
1055 |
@type inst: L{objects.Instance}
|
1056 |
@param inst: Instance object
|
1057 |
|
1058 |
"""
|
1059 |
consinfo = ctx.console[inst.name] |
1060 |
|
1061 |
if consinfo is None: |
1062 |
return _FS_UNAVAIL
|
1063 |
|
1064 |
return consinfo
|
1065 |
|
1066 |
|
1067 |
def _GetInstanceDiskFields(): |
1068 |
"""Get instance fields involving disks.
|
1069 |
|
1070 |
@return: List of field definitions used as input for L{_PrepareFieldList}
|
1071 |
|
1072 |
"""
|
1073 |
fields = [ |
1074 |
(_MakeField("disk_usage", "DiskUsage", QFT_UNIT, |
1075 |
"Total disk space used by instance on each of its nodes;"
|
1076 |
" this is not the disk size visible to the instance, but"
|
1077 |
" the usage on the node"),
|
1078 |
IQ_DISKUSAGE, _GetInstDiskUsage), |
1079 |
(_MakeField("disk.count", "Disks", QFT_NUMBER, "Number of disks"), |
1080 |
IQ_CONFIG, lambda ctx, inst: len(inst.disks)), |
1081 |
(_MakeField("disk.sizes", "Disk_sizes", QFT_OTHER, "List of disk sizes"), |
1082 |
IQ_CONFIG, lambda ctx, inst: [disk.size for disk in inst.disks]), |
1083 |
] |
1084 |
|
1085 |
# Disks by number
|
1086 |
fields.extend([ |
1087 |
(_MakeField("disk.size/%s" % i, "Disk/%s" % i, QFT_UNIT, |
1088 |
"Disk size of %s disk" % utils.FormatOrdinal(i + 1)), |
1089 |
IQ_CONFIG, _GetInstDiskSize(i)) |
1090 |
for i in range(constants.MAX_DISKS) |
1091 |
]) |
1092 |
|
1093 |
return fields
|
1094 |
|
1095 |
|
1096 |
def _GetInstanceParameterFields(): |
1097 |
"""Get instance fields involving parameters.
|
1098 |
|
1099 |
@return: List of field definitions used as input for L{_PrepareFieldList}
|
1100 |
|
1101 |
"""
|
1102 |
# TODO: Consider moving titles closer to constants
|
1103 |
be_title = { |
1104 |
constants.BE_AUTO_BALANCE: "Auto_balance",
|
1105 |
constants.BE_MEMORY: "ConfigMemory",
|
1106 |
constants.BE_VCPUS: "ConfigVCPUs",
|
1107 |
} |
1108 |
|
1109 |
hv_title = { |
1110 |
constants.HV_ACPI: "ACPI",
|
1111 |
constants.HV_BOOT_ORDER: "Boot_order",
|
1112 |
constants.HV_CDROM_IMAGE_PATH: "CDROM_image_path",
|
1113 |
constants.HV_DISK_TYPE: "Disk_type",
|
1114 |
constants.HV_INITRD_PATH: "Initrd_path",
|
1115 |
constants.HV_KERNEL_PATH: "Kernel_path",
|
1116 |
constants.HV_NIC_TYPE: "NIC_type",
|
1117 |
constants.HV_PAE: "PAE",
|
1118 |
constants.HV_VNC_BIND_ADDRESS: "VNC_bind_address",
|
1119 |
} |
1120 |
|
1121 |
fields = [ |
1122 |
# Filled parameters
|
1123 |
(_MakeField("hvparams", "HypervisorParameters", QFT_OTHER, |
1124 |
"Hypervisor parameters"),
|
1125 |
IQ_CONFIG, lambda ctx, _: ctx.inst_hvparams),
|
1126 |
(_MakeField("beparams", "BackendParameters", QFT_OTHER, |
1127 |
"Backend parameters"),
|
1128 |
IQ_CONFIG, lambda ctx, _: ctx.inst_beparams),
|
1129 |
|
1130 |
# Unfilled parameters
|
1131 |
(_MakeField("custom_hvparams", "CustomHypervisorParameters", QFT_OTHER, |
1132 |
"Custom hypervisor parameters"),
|
1133 |
IQ_CONFIG, _GetItemAttr("hvparams")),
|
1134 |
(_MakeField("custom_beparams", "CustomBackendParameters", QFT_OTHER, |
1135 |
"Custom backend parameters",),
|
1136 |
IQ_CONFIG, _GetItemAttr("beparams")),
|
1137 |
(_MakeField("custom_nicparams", "CustomNicParameters", QFT_OTHER, |
1138 |
"Custom network interface parameters"),
|
1139 |
IQ_CONFIG, lambda ctx, inst: [nic.nicparams for nic in inst.nics]), |
1140 |
] |
1141 |
|
1142 |
# HV params
|
1143 |
def _GetInstHvParam(name): |
1144 |
return lambda ctx, _: ctx.inst_hvparams.get(name, _FS_UNAVAIL) |
1145 |
|
1146 |
fields.extend([ |
1147 |
(_MakeField("hv/%s" % name, hv_title.get(name, "hv/%s" % name), |
1148 |
_VTToQFT[kind], "The \"%s\" hypervisor parameter" % name),
|
1149 |
IQ_CONFIG, _GetInstHvParam(name)) |
1150 |
for name, kind in constants.HVS_PARAMETER_TYPES.items() |
1151 |
if name not in constants.HVC_GLOBALS |
1152 |
]) |
1153 |
|
1154 |
# BE params
|
1155 |
def _GetInstBeParam(name): |
1156 |
return lambda ctx, _: ctx.inst_beparams.get(name, None) |
1157 |
|
1158 |
fields.extend([ |
1159 |
(_MakeField("be/%s" % name, be_title.get(name, "be/%s" % name), |
1160 |
_VTToQFT[kind], "The \"%s\" backend parameter" % name),
|
1161 |
IQ_CONFIG, _GetInstBeParam(name)) |
1162 |
for name, kind in constants.BES_PARAMETER_TYPES.items() |
1163 |
]) |
1164 |
|
1165 |
return fields
|
1166 |
|
1167 |
|
1168 |
_INST_SIMPLE_FIELDS = { |
1169 |
"disk_template": ("Disk_template", QFT_TEXT, "Instance disk template"), |
1170 |
"hypervisor": ("Hypervisor", QFT_TEXT, "Hypervisor name"), |
1171 |
"name": ("Instance", QFT_TEXT, "Instance name"), |
1172 |
# Depending on the hypervisor, the port can be None
|
1173 |
"network_port": ("Network_port", QFT_OTHER, |
1174 |
"Instance network port if available (e.g. for VNC console)"),
|
1175 |
"os": ("OS", QFT_TEXT, "Operating system"), |
1176 |
"serial_no": ("SerialNo", QFT_NUMBER, _SERIAL_NO_DOC % "Instance"), |
1177 |
"uuid": ("UUID", QFT_TEXT, "Instance UUID"), |
1178 |
} |
1179 |
|
1180 |
|
1181 |
def _BuildInstanceFields(): |
1182 |
"""Builds list of fields for instance queries.
|
1183 |
|
1184 |
"""
|
1185 |
fields = [ |
1186 |
(_MakeField("pnode", "Primary_node", QFT_TEXT, "Primary node"), IQ_CONFIG, |
1187 |
_GetItemAttr("primary_node")),
|
1188 |
(_MakeField("snodes", "Secondary_Nodes", QFT_OTHER, |
1189 |
"Secondary nodes; usually this will just be one node"),
|
1190 |
IQ_CONFIG, lambda ctx, inst: list(inst.secondary_nodes)), |
1191 |
(_MakeField("admin_state", "Autostart", QFT_BOOL, |
1192 |
"Desired state of instance (if set, the instance should be"
|
1193 |
" up)"),
|
1194 |
IQ_CONFIG, _GetItemAttr("admin_up")),
|
1195 |
(_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, |
1196 |
lambda ctx, inst: list(inst.GetTags())), |
1197 |
(_MakeField("console", "Console", QFT_OTHER, |
1198 |
"Instance console information"), IQ_CONSOLE,
|
1199 |
_GetInstanceConsole), |
1200 |
] |
1201 |
|
1202 |
# Add simple fields
|
1203 |
fields.extend([(_MakeField(name, title, kind, doc), |
1204 |
IQ_CONFIG, _GetItemAttr(name)) |
1205 |
for (name, (title, kind, doc)) in _INST_SIMPLE_FIELDS.items()]) |
1206 |
|
1207 |
# Fields requiring talking to the node
|
1208 |
fields.extend([ |
1209 |
(_MakeField("oper_state", "Running", QFT_BOOL, "Actual state of instance"), |
1210 |
IQ_LIVE, _GetInstOperState), |
1211 |
(_MakeField("oper_ram", "Memory", QFT_UNIT, |
1212 |
"Actual memory usage as seen by hypervisor"),
|
1213 |
IQ_LIVE, _GetInstLiveData("memory")),
|
1214 |
(_MakeField("oper_vcpus", "VCPUs", QFT_NUMBER, |
1215 |
"Actual number of VCPUs as seen by hypervisor"),
|
1216 |
IQ_LIVE, _GetInstLiveData("vcpus")),
|
1217 |
]) |
1218 |
|
1219 |
# Status field
|
1220 |
status_values = (constants.INSTST_RUNNING, constants.INSTST_ADMINDOWN, |
1221 |
constants.INSTST_WRONGNODE, constants.INSTST_ERRORUP, |
1222 |
constants.INSTST_ERRORDOWN, constants.INSTST_NODEDOWN, |
1223 |
constants.INSTST_NODEOFFLINE) |
1224 |
status_doc = ("Instance status; \"%s\" if instance is set to be running"
|
1225 |
" and actually is, \"%s\" if instance is stopped and"
|
1226 |
" is not running, \"%s\" if instance running, but not on its"
|
1227 |
" designated primary node, \"%s\" if instance should be"
|
1228 |
" stopped, but is actually running, \"%s\" if instance should"
|
1229 |
" run, but doesn't, \"%s\" if instance's primary node is down,"
|
1230 |
" \"%s\" if instance's primary node is marked offline" %
|
1231 |
status_values) |
1232 |
fields.append((_MakeField("status", "Status", QFT_TEXT, status_doc), |
1233 |
IQ_LIVE, _GetInstStatus)) |
1234 |
assert set(status_values) == constants.INSTST_ALL, \ |
1235 |
"Status documentation mismatch"
|
1236 |
|
1237 |
(network_fields, network_aliases) = _GetInstanceNetworkFields() |
1238 |
|
1239 |
fields.extend(network_fields) |
1240 |
fields.extend(_GetInstanceParameterFields()) |
1241 |
fields.extend(_GetInstanceDiskFields()) |
1242 |
fields.extend(_GetItemTimestampFields(IQ_CONFIG)) |
1243 |
|
1244 |
aliases = [ |
1245 |
("vcpus", "be/vcpus"), |
1246 |
("sda_size", "disk.size/0"), |
1247 |
("sdb_size", "disk.size/1"), |
1248 |
] + network_aliases |
1249 |
|
1250 |
return _PrepareFieldList(fields, aliases)
|
1251 |
|
1252 |
|
1253 |
class LockQueryData: |
1254 |
"""Data container for lock data queries.
|
1255 |
|
1256 |
"""
|
1257 |
def __init__(self, lockdata): |
1258 |
"""Initializes this class.
|
1259 |
|
1260 |
"""
|
1261 |
self.lockdata = lockdata
|
1262 |
|
1263 |
def __iter__(self): |
1264 |
"""Iterate over all locks.
|
1265 |
|
1266 |
"""
|
1267 |
return iter(self.lockdata) |
1268 |
|
1269 |
|
1270 |
def _GetLockOwners(_, data): |
1271 |
"""Returns a sorted list of a lock's current owners.
|
1272 |
|
1273 |
"""
|
1274 |
(_, _, owners, _) = data |
1275 |
|
1276 |
if owners:
|
1277 |
owners = utils.NiceSort(owners) |
1278 |
|
1279 |
return owners
|
1280 |
|
1281 |
|
1282 |
def _GetLockPending(_, data): |
1283 |
"""Returns a sorted list of a lock's pending acquires.
|
1284 |
|
1285 |
"""
|
1286 |
(_, _, _, pending) = data |
1287 |
|
1288 |
if pending:
|
1289 |
pending = [(mode, utils.NiceSort(names)) |
1290 |
for (mode, names) in pending] |
1291 |
|
1292 |
return pending
|
1293 |
|
1294 |
|
1295 |
def _BuildLockFields(): |
1296 |
"""Builds list of fields for lock queries.
|
1297 |
|
1298 |
"""
|
1299 |
return _PrepareFieldList([
|
1300 |
(_MakeField("name", "Name", QFT_TEXT, "Lock name"), None, |
1301 |
lambda ctx, (name, mode, owners, pending): name),
|
1302 |
(_MakeField("mode", "Mode", QFT_OTHER, |
1303 |
"Mode in which the lock is currently acquired"
|
1304 |
" (exclusive or shared)"),
|
1305 |
LQ_MODE, lambda ctx, (name, mode, owners, pending): mode),
|
1306 |
(_MakeField("owner", "Owner", QFT_OTHER, "Current lock owner(s)"), |
1307 |
LQ_OWNER, _GetLockOwners), |
1308 |
(_MakeField("pending", "Pending", QFT_OTHER, |
1309 |
"Threads waiting for the lock"),
|
1310 |
LQ_PENDING, _GetLockPending), |
1311 |
], []) |
1312 |
|
1313 |
|
1314 |
class GroupQueryData: |
1315 |
"""Data container for node group data queries.
|
1316 |
|
1317 |
"""
|
1318 |
def __init__(self, groups, group_to_nodes, group_to_instances): |
1319 |
"""Initializes this class.
|
1320 |
|
1321 |
@param groups: List of node group objects
|
1322 |
@type group_to_nodes: dict; group UUID as key
|
1323 |
@param group_to_nodes: Per-group list of nodes
|
1324 |
@type group_to_instances: dict; group UUID as key
|
1325 |
@param group_to_instances: Per-group list of (primary) instances
|
1326 |
|
1327 |
"""
|
1328 |
self.groups = groups
|
1329 |
self.group_to_nodes = group_to_nodes
|
1330 |
self.group_to_instances = group_to_instances
|
1331 |
|
1332 |
def __iter__(self): |
1333 |
"""Iterate over all node groups.
|
1334 |
|
1335 |
"""
|
1336 |
return iter(self.groups) |
1337 |
|
1338 |
|
1339 |
_GROUP_SIMPLE_FIELDS = { |
1340 |
"alloc_policy": ("AllocPolicy", QFT_TEXT, "Allocation policy for group"), |
1341 |
"name": ("Group", QFT_TEXT, "Group name"), |
1342 |
"serial_no": ("SerialNo", QFT_NUMBER, _SERIAL_NO_DOC % "Group"), |
1343 |
"uuid": ("UUID", QFT_TEXT, "Group UUID"), |
1344 |
"ndparams": ("NDParams", QFT_OTHER, "Node parameters"), |
1345 |
} |
1346 |
|
1347 |
|
1348 |
def _BuildGroupFields(): |
1349 |
"""Builds list of fields for node group queries.
|
1350 |
|
1351 |
"""
|
1352 |
# Add simple fields
|
1353 |
fields = [(_MakeField(name, title, kind, doc), GQ_CONFIG, _GetItemAttr(name)) |
1354 |
for (name, (title, kind, doc)) in _GROUP_SIMPLE_FIELDS.items()] |
1355 |
|
1356 |
def _GetLength(getter): |
1357 |
return lambda ctx, group: len(getter(ctx)[group.uuid]) |
1358 |
|
1359 |
def _GetSortedList(getter): |
1360 |
return lambda ctx, group: utils.NiceSort(getter(ctx)[group.uuid]) |
1361 |
|
1362 |
group_to_nodes = operator.attrgetter("group_to_nodes")
|
1363 |
group_to_instances = operator.attrgetter("group_to_instances")
|
1364 |
|
1365 |
# Add fields for nodes
|
1366 |
fields.extend([ |
1367 |
(_MakeField("node_cnt", "Nodes", QFT_NUMBER, "Number of nodes"), |
1368 |
GQ_NODE, _GetLength(group_to_nodes)), |
1369 |
(_MakeField("node_list", "NodeList", QFT_OTHER, "List of nodes"), |
1370 |
GQ_NODE, _GetSortedList(group_to_nodes)), |
1371 |
]) |
1372 |
|
1373 |
# Add fields for instances
|
1374 |
fields.extend([ |
1375 |
(_MakeField("pinst_cnt", "Instances", QFT_NUMBER, |
1376 |
"Number of primary instances"),
|
1377 |
GQ_INST, _GetLength(group_to_instances)), |
1378 |
(_MakeField("pinst_list", "InstanceList", QFT_OTHER, |
1379 |
"List of primary instances"),
|
1380 |
GQ_INST, _GetSortedList(group_to_instances)), |
1381 |
]) |
1382 |
|
1383 |
fields.extend(_GetItemTimestampFields(GQ_CONFIG)) |
1384 |
|
1385 |
return _PrepareFieldList(fields, [])
|
1386 |
|
1387 |
|
1388 |
#: Fields available for node queries
|
1389 |
NODE_FIELDS = _BuildNodeFields() |
1390 |
|
1391 |
#: Fields available for instance queries
|
1392 |
INSTANCE_FIELDS = _BuildInstanceFields() |
1393 |
|
1394 |
#: Fields available for lock queries
|
1395 |
LOCK_FIELDS = _BuildLockFields() |
1396 |
|
1397 |
#: Fields available for node group queries
|
1398 |
GROUP_FIELDS = _BuildGroupFields() |
1399 |
|
1400 |
#: All available field lists
|
1401 |
ALL_FIELD_LISTS = [NODE_FIELDS, INSTANCE_FIELDS, LOCK_FIELDS, GROUP_FIELDS] |