4 # Copyright (C) 2010, 2011, 2012, 2013 Google Inc.
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.
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.
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
22 """Module for query operations
26 - Add field definitions
27 - See how L{NODE_FIELDS} is built
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
34 - Value data type, e.g. L{constants.QFT_NUMBER}
35 - Human-readable description, must not end with punctuation or
37 - Data request type, see e.g. C{NQ_*}
38 - OR-ed flags, see C{QFF_*}
39 - A retrieval function, see L{Query.__init__} for description
40 - Pass list of fields through L{_PrepareFieldList} for preparation and
42 - Instantiate L{Query} with prepared field list definition and selected fields
43 - Call L{Query.RequestedData} to determine what data to collect/compute
44 - Call L{Query.Query} or L{Query.OldStyleQuery} with collected data and use
46 - Data container must support iteration using C{__iter__}
47 - Items are passed to retrieval functions and can have any format
48 - Call L{Query.GetFields} to get list of definitions for selected fields
50 @attention: Retrieval functions must be idempotent. They can be called multiple
51 times, in any order and any number of times.
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
65 from ganeti import runtime
66 from ganeti import qlang
67 from ganeti import jstore
69 from ganeti.constants import (QFT_UNKNOWN, QFT_TEXT, QFT_BOOL, QFT_NUMBER,
70 QFT_UNIT, QFT_TIMESTAMP, QFT_OTHER,
71 RS_NORMAL, RS_UNKNOWN, RS_NODATA,
72 RS_UNAVAIL, RS_OFFLINE)
77 NETQ_INST) = range(300, 304)
79 # Constants for requesting data from the caller/data provider. Each property
80 # collected/computed separately by the data provider should have its own to
81 # only collect the requested data and not more.
94 IQ_NETWORKS) = range(100, 106)
98 LQ_PENDING) = range(10, 13)
103 GQ_DISKPARAMS) = range(200, 204)
107 CQ_WATCHER_PAUSE) = range(300, 303)
109 (JQ_ARCHIVED, ) = range(400, 401)
113 QFF_IP_ADDRESS = 0x02
115 QFF_SPLIT_TIMESTAMP = 0x08
116 # Next values: 0x10, 0x20, 0x40, 0x80, 0x100, 0x200
117 QFF_ALL = (QFF_HOSTNAME | QFF_IP_ADDRESS | QFF_JOB_ID | QFF_SPLIT_TIMESTAMP)
119 FIELD_NAME_RE = re.compile(r"^[a-z0-9/._]+$")
120 TITLE_RE = re.compile(r"^[^\s]+$")
121 DOC_RE = re.compile(r"^[A-Z].*[^.,?!]$")
123 #: Verification function for each field type
125 QFT_UNKNOWN: ht.TNone,
126 QFT_TEXT: ht.TString,
130 QFT_TIMESTAMP: ht.TNumber,
131 QFT_OTHER: lambda _: True,
134 # Unique objects for special field statuses
135 _FS_UNKNOWN = object()
136 _FS_NODATA = object()
137 _FS_UNAVAIL = object()
138 _FS_OFFLINE = object()
140 #: List of all special status
141 _FS_ALL = compat.UniqueFrozenset([
148 #: VType to QFT mapping
150 # TODO: fix validation of empty strings
151 constants.VTYPE_STRING: QFT_OTHER, # since VTYPE_STRINGs can be empty
152 constants.VTYPE_MAYBE_STRING: QFT_OTHER,
153 constants.VTYPE_BOOL: QFT_BOOL,
154 constants.VTYPE_SIZE: QFT_UNIT,
155 constants.VTYPE_INT: QFT_NUMBER,
158 _SERIAL_NO_DOC = "%s object serial number, incremented on each modification"
161 def _GetUnknownField(ctx, item): # pylint: disable=W0613
162 """Gets the contents of an unknown field.
168 def _GetQueryFields(fielddefs, selected):
169 """Calculates the internal list of selected fields.
171 Unknown fields are returned as L{constants.QFT_UNKNOWN}.
173 @type fielddefs: dict
174 @param fielddefs: Field definitions
175 @type selected: list of strings
176 @param selected: List of selected fields
181 for name in selected:
183 fdef = fielddefs[name]
185 fdef = (_MakeField(name, name, QFT_UNKNOWN, "Unknown field '%s'" % name),
186 None, 0, _GetUnknownField)
188 assert len(fdef) == 4
195 def GetAllFields(fielddefs):
196 """Extract L{objects.QueryFieldDefinition} from field definitions.
198 @rtype: list of L{objects.QueryFieldDefinition}
201 return [fdef for (fdef, _, _, _) in fielddefs]
205 """Class for filter analytics.
207 When filters are used, the user of the L{Query} class usually doesn't know
208 exactly which items will be necessary for building the result. It therefore
209 has to prepare and compute the input data for potentially returning
212 There are two ways to optimize this. The first, and simpler, is to assign
213 each field a group of data, so that the caller can determine which
214 computations are necessary depending on the data groups requested. The list
215 of referenced groups must also be computed for fields referenced in the
218 The second is restricting the items based on a primary key. The primary key
219 is usually a unique name (e.g. a node name). This class extracts all
220 referenced names from a filter. If it encounters any filter condition which
221 disallows such a list to be determined (e.g. a non-equality filter), all
222 names will be requested.
224 The end-effect is that any operation other than L{qlang.OP_OR} and
225 L{qlang.OP_EQUAL} will make the query more expensive.
228 def __init__(self, namefield):
229 """Initializes this class.
231 @type namefield: string
232 @param namefield: Field caller is interested in
235 self._namefield = namefield
237 #: Whether all names need to be requested (e.g. if a non-equality operator
239 self._allnames = False
241 #: Which names to request
244 #: Data kinds referenced by the filter (used by L{Query.RequestedData})
245 self._datakinds = set()
247 def RequestedNames(self):
248 """Returns all requested values.
250 Returns C{None} if list of values can't be determined (e.g. encountered
251 non-equality operators).
256 if self._allnames or self._names is None:
259 return utils.UniqueSequence(self._names)
261 def ReferencedData(self):
262 """Returns all kinds of data referenced by the filter.
265 return frozenset(self._datakinds)
267 def _NeedAllNames(self):
268 """Changes internal state to request all names.
271 self._allnames = True
274 def NoteLogicOp(self, op):
275 """Called when handling a logic operation.
281 if op != qlang.OP_OR:
284 def NoteUnaryOp(self, op, datakind): # pylint: disable=W0613
285 """Called when handling an unary operation.
291 if datakind is not None:
292 self._datakinds.add(datakind)
296 def NoteBinaryOp(self, op, datakind, name, value):
297 """Called when handling a binary operation.
302 @param name: Left-hand side of operator (field name)
303 @param value: Right-hand side of operator
306 if datakind is not None:
307 self._datakinds.add(datakind)
312 # If any operator other than equality was used, all names need to be
314 if op == qlang.OP_EQUAL and name == self._namefield:
315 if self._names is None:
317 self._names.append(value)
322 def _WrapLogicOp(op_fn, sentences, ctx, item):
323 """Wrapper for logic operator functions.
326 return op_fn(fn(ctx, item) for fn in sentences)
329 def _WrapUnaryOp(op_fn, inner, ctx, item):
330 """Wrapper for unary operator functions.
333 return op_fn(inner(ctx, item))
336 def _WrapBinaryOp(op_fn, retrieval_fn, value, ctx, item):
337 """Wrapper for binary operator functions.
340 return op_fn(retrieval_fn(ctx, item), value)
343 def _WrapNot(fn, lhs, rhs):
344 """Negates the result of a wrapped function.
347 return not fn(lhs, rhs)
350 def _PrepareRegex(pattern):
351 """Compiles a regular expression.
355 return re.compile(pattern)
356 except re.error, err:
357 raise errors.ParameterError("Invalid regex pattern (%s)" % err)
360 def _PrepareSplitTimestamp(value):
361 """Prepares a value for comparison by L{_MakeSplitTimestampComparison}.
364 if ht.TNumber(value):
367 return utils.MergeTime(value)
370 def _MakeSplitTimestampComparison(fn):
371 """Compares split timestamp values after converting to float.
374 return lambda lhs, rhs: fn(utils.MergeTime(lhs), rhs)
377 def _MakeComparisonChecks(fn):
378 """Prepares flag-specific comparisons using a comparison function.
382 (QFF_SPLIT_TIMESTAMP, _MakeSplitTimestampComparison(fn),
383 _PrepareSplitTimestamp),
384 (QFF_JOB_ID, lambda lhs, rhs: fn(jstore.ParseJobId(lhs), rhs),
390 class _FilterCompilerHelper:
391 """Converts a query filter to a callable usable for filtering.
394 # String statement has no effect, pylint: disable=W0105
396 #: How deep filters can be nested
399 # Unique identifiers for operator groups
402 _OPTYPE_BINARY) = range(1, 4)
404 """Functions for equality checks depending on field flags.
406 List of tuples containing flags and a callable receiving the left- and
407 right-hand side of the operator. The flags are an OR-ed value of C{QFF_*}
408 (e.g. L{QFF_HOSTNAME} or L{QFF_SPLIT_TIMESTAMP}).
410 Order matters. The first item with flags will be used. Flags are checked
416 lambda lhs, rhs: utils.MatchNameComponent(rhs, [lhs],
417 case_sensitive=False),
419 (QFF_SPLIT_TIMESTAMP, _MakeSplitTimestampComparison(operator.eq),
420 _PrepareSplitTimestamp),
421 (None, operator.eq, None),
426 Operator as key (C{qlang.OP_*}), value a tuple of operator group
427 (C{_OPTYPE_*}) and a group-specific value:
429 - C{_OPTYPE_LOGIC}: Callable taking any number of arguments; used by
431 - C{_OPTYPE_UNARY}: Always C{None}; details handled by L{_HandleUnaryOp}
432 - C{_OPTYPE_BINARY}: Callable taking exactly two parameters, the left- and
433 right-hand side of the operator, used by L{_HandleBinaryOp}
438 qlang.OP_OR: (_OPTYPE_LOGIC, compat.any),
439 qlang.OP_AND: (_OPTYPE_LOGIC, compat.all),
442 qlang.OP_NOT: (_OPTYPE_UNARY, None),
443 qlang.OP_TRUE: (_OPTYPE_UNARY, None),
446 qlang.OP_EQUAL: (_OPTYPE_BINARY, _EQUALITY_CHECKS),
448 (_OPTYPE_BINARY, [(flags, compat.partial(_WrapNot, fn), valprepfn)
449 for (flags, fn, valprepfn) in _EQUALITY_CHECKS]),
450 qlang.OP_LT: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.lt)),
451 qlang.OP_LE: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.le)),
452 qlang.OP_GT: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.gt)),
453 qlang.OP_GE: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.ge)),
454 qlang.OP_REGEXP: (_OPTYPE_BINARY, [
455 (None, lambda lhs, rhs: rhs.search(lhs), _PrepareRegex),
457 qlang.OP_CONTAINS: (_OPTYPE_BINARY, [
458 (None, operator.contains, None),
462 def __init__(self, fields):
463 """Initializes this class.
465 @param fields: Field definitions (return value of L{_PrepareFieldList})
468 self._fields = fields
470 self._op_handler = None
472 def __call__(self, hints, qfilter):
473 """Converts a query filter into a callable function.
475 @type hints: L{_FilterHints} or None
476 @param hints: Callbacks doing analysis on filter
478 @param qfilter: Filter structure
480 @return: Function receiving context and item as parameters, returning
481 boolean as to whether item matches filter
486 (self._HandleLogicOp, getattr(hints, "NoteLogicOp", None)),
488 (self._HandleUnaryOp, getattr(hints, "NoteUnaryOp", None)),
490 (self._HandleBinaryOp, getattr(hints, "NoteBinaryOp", None)),
494 filter_fn = self._Compile(qfilter, 0)
496 self._op_handler = None
500 def _Compile(self, qfilter, level):
501 """Inner function for converting filters.
503 Calls the correct handler functions for the top-level operator. This
504 function is called recursively (e.g. for logic operators).
507 if not (isinstance(qfilter, (list, tuple)) and qfilter):
508 raise errors.ParameterError("Invalid filter on level %s" % level)
511 if level >= self._LEVELS_MAX:
512 raise errors.ParameterError("Only up to %s levels are allowed (filter"
513 " nested too deep)" % self._LEVELS_MAX)
515 # Create copy to be modified
516 operands = qfilter[:]
520 (kind, op_data) = self._OPS[op]
522 raise errors.ParameterError("Unknown operator '%s'" % op)
524 (handler, hints_cb) = self._op_handler[kind]
526 return handler(hints_cb, level, op, op_data, operands)
528 def _LookupField(self, name):
529 """Returns a field definition by name.
533 return self._fields[name]
535 raise errors.ParameterError("Unknown field '%s'" % name)
537 def _HandleLogicOp(self, hints_fn, level, op, op_fn, operands):
538 """Handles logic operators.
540 @type hints_fn: callable
541 @param hints_fn: Callback doing some analysis on the filter
543 @param level: Current depth
546 @type op_fn: callable
547 @param op_fn: Function implementing operator
549 @param operands: List of operands
555 return compat.partial(_WrapLogicOp, op_fn,
556 [self._Compile(op, level + 1) for op in operands])
558 def _HandleUnaryOp(self, hints_fn, level, op, op_fn, operands):
559 """Handles unary operators.
561 @type hints_fn: callable
562 @param hints_fn: Callback doing some analysis on the filter
564 @param level: Current depth
567 @type op_fn: callable
568 @param op_fn: Function implementing operator
570 @param operands: List of operands
575 if len(operands) != 1:
576 raise errors.ParameterError("Unary operator '%s' expects exactly one"
579 if op == qlang.OP_TRUE:
580 (_, datakind, _, retrieval_fn) = self._LookupField(operands[0])
583 hints_fn(op, datakind)
585 op_fn = operator.truth
587 elif op == qlang.OP_NOT:
591 op_fn = operator.not_
592 arg = self._Compile(operands[0], level + 1)
594 raise errors.ProgrammerError("Can't handle operator '%s'" % op)
596 return compat.partial(_WrapUnaryOp, op_fn, arg)
598 def _HandleBinaryOp(self, hints_fn, level, op, op_data, operands):
599 """Handles binary operators.
601 @type hints_fn: callable
602 @param hints_fn: Callback doing some analysis on the filter
604 @param level: Current depth
607 @param op_data: Functions implementing operators
609 @param operands: List of operands
612 # Unused arguments, pylint: disable=W0613
614 (name, value) = operands
615 except (ValueError, TypeError):
616 raise errors.ParameterError("Invalid binary operator, expected exactly"
619 (fdef, datakind, field_flags, retrieval_fn) = self._LookupField(name)
621 assert fdef.kind != QFT_UNKNOWN
623 # TODO: Type conversions?
625 verify_fn = _VERIFY_FN[fdef.kind]
626 if not verify_fn(value):
627 raise errors.ParameterError("Unable to compare field '%s' (type '%s')"
628 " with '%s', expected %s" %
629 (name, fdef.kind, value.__class__.__name__,
633 hints_fn(op, datakind, name, value)
635 for (fn_flags, fn, valprepfn) in op_data:
636 if fn_flags is None or fn_flags & field_flags:
637 # Prepare value if necessary (e.g. compile regular expression)
639 value = valprepfn(value)
641 return compat.partial(_WrapBinaryOp, fn, retrieval_fn, value)
643 raise errors.ProgrammerError("Unable to find operator implementation"
644 " (op '%s', flags %s)" % (op, field_flags))
647 def _CompileFilter(fields, hints, qfilter):
648 """Converts a query filter into a callable function.
650 See L{_FilterCompilerHelper} for details.
655 return _FilterCompilerHelper(fields)(hints, qfilter)
659 def __init__(self, fieldlist, selected, qfilter=None, namefield=None):
660 """Initializes this class.
662 The field definition is a dictionary with the field's name as a key and a
663 tuple containing, in order, the field definition object
664 (L{objects.QueryFieldDefinition}, the data kind to help calling code
665 collect data and a retrieval function. The retrieval function is called
666 with two parameters, in order, the data container and the item in container
667 (see L{Query.Query}).
669 Users of this class can call L{RequestedData} before preparing the data
670 container to determine what data is needed.
672 @type fieldlist: dictionary
673 @param fieldlist: Field definitions
674 @type selected: list of strings
675 @param selected: List of selected fields
678 assert namefield is None or namefield in fieldlist
680 self._fields = _GetQueryFields(fieldlist, selected)
682 self._filter_fn = None
683 self._requested_names = None
684 self._filter_datakinds = frozenset()
686 if qfilter is not None:
687 # Collect requested names if wanted
689 hints = _FilterHints(namefield)
693 # Build filter function
694 self._filter_fn = _CompileFilter(fieldlist, hints, qfilter)
696 self._requested_names = hints.RequestedNames()
697 self._filter_datakinds = hints.ReferencedData()
699 if namefield is None:
702 (_, _, _, self._name_fn) = fieldlist[namefield]
704 def RequestedNames(self):
705 """Returns all names referenced in the filter.
707 If there is no filter or operators are preventing determining the exact
708 names, C{None} is returned.
711 return self._requested_names
713 def RequestedData(self):
714 """Gets requested kinds of data.
719 return (self._filter_datakinds |
720 frozenset(datakind for (_, datakind, _, _) in self._fields
721 if datakind is not None))
724 """Returns the list of fields for this query.
726 Includes unknown fields.
728 @rtype: List of L{objects.QueryFieldDefinition}
731 return GetAllFields(self._fields)
733 def Query(self, ctx, sort_by_name=True):
736 @param ctx: Data container passed to field retrieval functions, must
737 support iteration using C{__iter__}
738 @type sort_by_name: boolean
739 @param sort_by_name: Whether to sort by name or keep the input data's
743 sort = (self._name_fn and sort_by_name)
747 for idx, item in enumerate(ctx):
748 if not (self._filter_fn is None or self._filter_fn(ctx, item)):
751 row = [_ProcessResult(fn(ctx, item)) for (_, _, _, fn) in self._fields]
755 _VerifyResultRow(self._fields, row)
758 (status, name) = _ProcessResult(self._name_fn(ctx, item))
759 assert status == constants.RS_NORMAL
760 # TODO: Are there cases where we wouldn't want to use NiceSort?
761 # Answer: if the name field is non-string...
762 result.append((utils.NiceSortKey(name), idx, row))
769 # TODO: Would "heapq" be more efficient than sorting?
771 # Sorting in-place instead of using "sorted()"
774 assert not result or (len(result[0]) == 3 and len(result[-1]) == 3)
776 return map(operator.itemgetter(2), result)
778 def OldStyleQuery(self, ctx, sort_by_name=True):
779 """Query with "old" query result format.
781 See L{Query.Query} for arguments.
784 unknown = set(fdef.name for (fdef, _, _, _) in self._fields
785 if fdef.kind == QFT_UNKNOWN)
787 raise errors.OpPrereqError("Unknown output fields selected: %s" %
788 (utils.CommaJoin(unknown), ),
791 return [[value for (_, value) in row]
792 for row in self.Query(ctx, sort_by_name=sort_by_name)]
795 def _ProcessResult(value):
796 """Converts result values into externally-visible ones.
799 if value is _FS_UNKNOWN:
800 return (RS_UNKNOWN, None)
801 elif value is _FS_NODATA:
802 return (RS_NODATA, None)
803 elif value is _FS_UNAVAIL:
804 return (RS_UNAVAIL, None)
805 elif value is _FS_OFFLINE:
806 return (RS_OFFLINE, None)
808 return (RS_NORMAL, value)
811 def _VerifyResultRow(fields, row):
812 """Verifies the contents of a query result row.
815 @param fields: Field definitions for result
816 @type row: list of tuples
820 assert len(row) == len(fields)
822 for ((status, value), (fdef, _, _, _)) in zip(row, fields):
823 if status == RS_NORMAL:
824 if not _VERIFY_FN[fdef.kind](value):
825 errs.append("normal field %s fails validation (value is %s)" %
827 elif value is not None:
828 errs.append("abnormal field %s has a non-None value" % fdef.name)
829 assert not errs, ("Failed validation: %s in row %s" %
830 (utils.CommaJoin(errs), row))
833 def _FieldDictKey((fdef, _, flags, fn)):
834 """Generates key for field dictionary.
837 assert fdef.name and fdef.title, "Name and title are required"
838 assert FIELD_NAME_RE.match(fdef.name)
839 assert TITLE_RE.match(fdef.title)
840 assert (DOC_RE.match(fdef.doc) and len(fdef.doc.splitlines()) == 1 and
841 fdef.doc.strip() == fdef.doc), \
842 "Invalid description for field '%s'" % fdef.name
844 assert (flags & ~QFF_ALL) == 0, "Unknown flags for field '%s'" % fdef.name
849 def _PrepareFieldList(fields, aliases):
850 """Prepares field list for use by L{Query}.
852 Converts the list to a dictionary and does some verification.
854 @type fields: list of tuples; (L{objects.QueryFieldDefinition}, data
855 kind, retrieval function)
856 @param fields: List of fields, see L{Query.__init__} for a better
858 @type aliases: list of tuples; (alias, target)
859 @param aliases: list of tuples containing aliases; for each
860 alias/target pair, a duplicate will be created in the field list
862 @return: Field dictionary for L{Query}
866 duplicates = utils.FindDuplicates(fdef.title.lower()
867 for (fdef, _, _, _) in fields)
868 assert not duplicates, "Duplicate title(s) found: %r" % duplicates
870 result = utils.SequenceToDict(fields, key=_FieldDictKey)
872 for alias, target in aliases:
873 assert alias not in result, "Alias %s overrides an existing field" % alias
874 assert target in result, "Missing target %s for alias %s" % (target, alias)
875 (fdef, k, flags, fn) = result[target]
878 result[alias] = (fdef, k, flags, fn)
880 assert len(result) == len(fields) + len(aliases)
881 assert compat.all(name == fdef.name
882 for (name, (fdef, _, _, _)) in result.items())
887 def GetQueryResponse(query, ctx, sort_by_name=True):
888 """Prepares the response for a query.
890 @type query: L{Query}
891 @param ctx: Data container, see L{Query.Query}
892 @type sort_by_name: boolean
893 @param sort_by_name: Whether to sort by name or keep the input data's
897 return objects.QueryResponse(data=query.Query(ctx, sort_by_name=sort_by_name),
898 fields=query.GetFields()).ToDict()
901 def QueryFields(fielddefs, selected):
902 """Returns list of available fields.
904 @type fielddefs: dict
905 @param fielddefs: Field definitions
906 @type selected: list of strings
907 @param selected: List of selected fields
908 @return: List of L{objects.QueryFieldDefinition}
912 # Client requests all fields, sort by name
913 fdefs = utils.NiceSort(GetAllFields(fielddefs.values()),
914 key=operator.attrgetter("name"))
916 # Keep order as requested by client
917 fdefs = Query(fielddefs, selected).GetFields()
919 return objects.QueryFieldsResponse(fields=fdefs).ToDict()
922 def _MakeField(name, title, kind, doc):
923 """Wrapper for creating L{objects.QueryFieldDefinition} instances.
925 @param name: Field name as a regular expression
926 @param title: Human-readable title
927 @param kind: Field type
928 @param doc: Human-readable description
931 return objects.QueryFieldDefinition(name=name, title=title, kind=kind,
935 def _StaticValueInner(value, ctx, _): # pylint: disable=W0613
936 """Returns a static value.
942 def _StaticValue(value):
943 """Prepares a function to return a static value.
946 return compat.partial(_StaticValueInner, value)
949 def _GetNodeRole(node, master_name):
950 """Determine node role.
952 @type node: L{objects.Node}
953 @param node: Node object
954 @type master_name: string
955 @param master_name: Master node name
958 if node.name == master_name:
959 return constants.NR_MASTER
960 elif node.master_candidate:
961 return constants.NR_MCANDIDATE
963 return constants.NR_DRAINED
965 return constants.NR_OFFLINE
967 return constants.NR_REGULAR
970 def _GetItemAttr(attr):
971 """Returns a field function to return an attribute of the item.
973 @param attr: Attribute name
976 getter = operator.attrgetter(attr)
977 return lambda _, item: getter(item)
980 def _GetItemMaybeAttr(attr):
981 """Returns a field function to return a not-None attribute of the item.
983 If the value is None, then C{_FS_UNAVAIL} will be returned instead.
985 @param attr: Attribute name
989 val = getattr(obj, attr)
997 def _GetNDParam(name):
998 """Return a field function to return an ND parameter out of the context.
1001 def _helper(ctx, _):
1002 if ctx.ndparams is None:
1005 return ctx.ndparams.get(name, None)
1009 def _BuildNDFields(is_group):
1010 """Builds all the ndparam fields.
1012 @param is_group: whether this is called at group or node level
1016 field_kind = GQ_CONFIG
1018 field_kind = NQ_GROUP
1019 return [(_MakeField("ndp/%s" % name,
1020 constants.NDS_PARAMETER_TITLES.get(name,
1022 _VTToQFT[kind], "The \"%s\" node parameter" % name),
1023 field_kind, 0, _GetNDParam(name))
1024 for name, kind in constants.NDS_PARAMETER_TYPES.items()]
1027 def _ConvWrapInner(convert, fn, ctx, item):
1028 """Wrapper for converting values.
1030 @param convert: Conversion function receiving value as single parameter
1031 @param fn: Retrieval function
1034 value = fn(ctx, item)
1036 # Is the value an abnormal status?
1037 if compat.any(value is fs for fs in _FS_ALL):
1041 # TODO: Should conversion function also receive context, item or both?
1042 return convert(value)
1045 def _ConvWrap(convert, fn):
1046 """Convenience wrapper for L{_ConvWrapInner}.
1048 @param convert: Conversion function receiving value as single parameter
1049 @param fn: Retrieval function
1052 return compat.partial(_ConvWrapInner, convert, fn)
1055 def _GetItemTimestamp(getter):
1056 """Returns function for getting timestamp of item.
1058 @type getter: callable
1059 @param getter: Function to retrieve timestamp attribute
1063 """Returns a timestamp of item.
1066 timestamp = getter(item)
1067 if timestamp is None:
1068 # Old configs might not have all timestamps
1076 def _GetItemTimestampFields(datatype):
1077 """Returns common timestamp fields.
1079 @param datatype: Field data type for use by L{Query.RequestedData}
1083 (_MakeField("ctime", "CTime", QFT_TIMESTAMP, "Creation timestamp"),
1084 datatype, 0, _GetItemTimestamp(operator.attrgetter("ctime"))),
1085 (_MakeField("mtime", "MTime", QFT_TIMESTAMP, "Modification timestamp"),
1086 datatype, 0, _GetItemTimestamp(operator.attrgetter("mtime"))),
1090 class NodeQueryData:
1091 """Data container for node data queries.
1094 def __init__(self, nodes, live_data, master_uuid, node_to_primary,
1095 node_to_secondary, groups, oob_support, cluster):
1096 """Initializes this class.
1100 self.live_data = live_data
1101 self.master_uuid = master_uuid
1102 self.node_to_primary = node_to_primary
1103 self.node_to_secondary = node_to_secondary
1104 self.groups = groups
1105 self.oob_support = oob_support
1106 self.cluster = cluster
1108 # Used for individual rows
1109 self.curlive_data = None
1110 self.ndparams = None
1113 """Iterate over all nodes.
1115 This function has side-effects and only one instance of the resulting
1116 generator should be used at a time.
1119 for node in self.nodes:
1120 group = self.groups.get(node.group, None)
1122 self.ndparams = None
1124 self.ndparams = self.cluster.FillND(node, group)
1126 self.curlive_data = self.live_data.get(node.uuid, None)
1128 self.curlive_data = None
1132 #: Fields that are direct attributes of an L{objects.Node} object
1133 _NODE_SIMPLE_FIELDS = {
1134 "drained": ("Drained", QFT_BOOL, 0, "Whether node is drained"),
1135 "master_candidate": ("MasterC", QFT_BOOL, 0,
1136 "Whether node is a master candidate"),
1137 "master_capable": ("MasterCapable", QFT_BOOL, 0,
1138 "Whether node can become a master candidate"),
1139 "name": ("Node", QFT_TEXT, QFF_HOSTNAME, "Node name"),
1140 "offline": ("Offline", QFT_BOOL, 0, "Whether node is marked offline"),
1141 "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Node"),
1142 "uuid": ("UUID", QFT_TEXT, 0, "Node UUID"),
1143 "vm_capable": ("VMCapable", QFT_BOOL, 0, "Whether node can host instances"),
1147 #: Fields requiring talking to the node
1148 # Note that none of these are available for non-vm_capable nodes
1149 _NODE_LIVE_FIELDS = {
1150 "bootid": ("BootID", QFT_TEXT, "bootid",
1151 "Random UUID renewed for each system reboot, can be used"
1152 " for detecting reboots by tracking changes"),
1153 "cnodes": ("CNodes", QFT_NUMBER, "cpu_nodes",
1154 "Number of NUMA domains on node (if exported by hypervisor)"),
1155 "csockets": ("CSockets", QFT_NUMBER, "cpu_sockets",
1156 "Number of physical CPU sockets (if exported by hypervisor)"),
1157 "ctotal": ("CTotal", QFT_NUMBER, "cpu_total", "Number of logical processors"),
1158 "dfree": ("DFree", QFT_UNIT, "vg_free",
1159 "Available disk space in volume group"),
1160 "dtotal": ("DTotal", QFT_UNIT, "vg_size",
1161 "Total disk space in volume group used for instance disk"
1163 "spfree": ("SpFree", QFT_NUMBER, "spindles_free",
1164 "Available spindles in volume group (exclusive storage only)"),
1165 "sptotal": ("SpTotal", QFT_NUMBER, "spindles_total",
1166 "Total spindles in volume group (exclusive storage only)"),
1167 "mfree": ("MFree", QFT_UNIT, "memory_free",
1168 "Memory available for instance allocations"),
1169 "mnode": ("MNode", QFT_UNIT, "memory_dom0",
1170 "Amount of memory used by node (dom0 for Xen)"),
1171 "mtotal": ("MTotal", QFT_UNIT, "memory_total",
1172 "Total amount of memory of physical machine"),
1177 """Build function for calling another function with an node group.
1179 @param cb: The callback to be called with the nodegroup
1183 """Get group data for a node.
1185 @type ctx: L{NodeQueryData}
1186 @type inst: L{objects.Node}
1187 @param inst: Node object
1190 ng = ctx.groups.get(node.group, None)
1192 # Nodes always have a group, or the configuration is corrupt
1195 return cb(ctx, node, ng)
1200 def _GetNodeGroup(ctx, node, ng): # pylint: disable=W0613
1201 """Returns the name of a node's group.
1203 @type ctx: L{NodeQueryData}
1204 @type node: L{objects.Node}
1205 @param node: Node object
1206 @type ng: L{objects.NodeGroup}
1207 @param ng: The node group this node belongs to
1213 def _GetNodePower(ctx, node):
1214 """Returns the node powered state
1216 @type ctx: L{NodeQueryData}
1217 @type node: L{objects.Node}
1218 @param node: Node object
1221 if ctx.oob_support[node.uuid]:
1227 def _GetNdParams(ctx, node, ng):
1228 """Returns the ndparams for this node.
1230 @type ctx: L{NodeQueryData}
1231 @type node: L{objects.Node}
1232 @param node: Node object
1233 @type ng: L{objects.NodeGroup}
1234 @param ng: The node group this node belongs to
1237 return ctx.cluster.SimpleFillND(ng.FillND(node))
1240 def _GetLiveNodeField(field, kind, ctx, node):
1241 """Gets the value of a "live" field from L{NodeQueryData}.
1243 @param field: Live field name
1244 @param kind: Data kind, one of L{constants.QFT_ALL}
1245 @type ctx: L{NodeQueryData}
1246 @type node: L{objects.Node}
1247 @param node: Node object
1253 if not node.vm_capable:
1256 if not ctx.curlive_data:
1259 return _GetStatsField(field, kind, ctx.curlive_data)
1262 def _GetStatsField(field, kind, data):
1263 """Gets a value from live statistics.
1265 If the value is not found, L{_FS_UNAVAIL} is returned. If the field kind is
1266 numeric a conversion to integer is attempted. If that fails, L{_FS_UNAVAIL}
1269 @param field: Live field name
1270 @param kind: Data kind, one of L{constants.QFT_ALL}
1272 @param data: Statistics
1280 if kind == QFT_TEXT:
1283 assert kind in (QFT_NUMBER, QFT_UNIT)
1285 # Try to convert into number
1288 except (ValueError, TypeError):
1289 logging.exception("Failed to convert node field '%s' (value %r) to int",
1294 def _GetNodeHvState(_, node):
1295 """Converts node's hypervisor state for query result.
1298 hv_state = node.hv_state
1300 if hv_state is None:
1303 return dict((name, value.ToDict()) for (name, value) in hv_state.items())
1306 def _GetNodeDiskState(_, node):
1307 """Converts node's disk state for query result.
1310 disk_state = node.disk_state
1312 if disk_state is None:
1315 return dict((disk_kind, dict((name, value.ToDict())
1316 for (name, value) in kind_state.items()))
1317 for (disk_kind, kind_state) in disk_state.items())
1320 def _BuildNodeFields():
1321 """Builds list of fields for node queries.
1325 (_MakeField("pip", "PrimaryIP", QFT_TEXT, "Primary IP address"),
1326 NQ_CONFIG, 0, _GetItemAttr("primary_ip")),
1327 (_MakeField("sip", "SecondaryIP", QFT_TEXT, "Secondary IP address"),
1328 NQ_CONFIG, 0, _GetItemAttr("secondary_ip")),
1329 (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), NQ_CONFIG, 0,
1330 lambda ctx, node: list(node.GetTags())),
1331 (_MakeField("master", "IsMaster", QFT_BOOL, "Whether node is master"),
1332 NQ_CONFIG, 0, lambda ctx, node: node.uuid == ctx.master_uuid),
1333 (_MakeField("group", "Group", QFT_TEXT, "Node group"), NQ_GROUP, 0,
1334 _GetGroup(_GetNodeGroup)),
1335 (_MakeField("group.uuid", "GroupUUID", QFT_TEXT, "UUID of node group"),
1336 NQ_CONFIG, 0, _GetItemAttr("group")),
1337 (_MakeField("powered", "Powered", QFT_BOOL,
1338 "Whether node is thought to be powered on"),
1339 NQ_OOB, 0, _GetNodePower),
1340 (_MakeField("ndparams", "NodeParameters", QFT_OTHER,
1341 "Merged node parameters"),
1342 NQ_GROUP, 0, _GetGroup(_GetNdParams)),
1343 (_MakeField("custom_ndparams", "CustomNodeParameters", QFT_OTHER,
1344 "Custom node parameters"),
1345 NQ_GROUP, 0, _GetItemAttr("ndparams")),
1346 (_MakeField("hv_state", "HypervisorState", QFT_OTHER, "Hypervisor state"),
1347 NQ_CONFIG, 0, _GetNodeHvState),
1348 (_MakeField("disk_state", "DiskState", QFT_OTHER, "Disk state"),
1349 NQ_CONFIG, 0, _GetNodeDiskState),
1352 fields.extend(_BuildNDFields(False))
1355 role_values = (constants.NR_MASTER, constants.NR_MCANDIDATE,
1356 constants.NR_REGULAR, constants.NR_DRAINED,
1357 constants.NR_OFFLINE)
1358 role_doc = ("Node role; \"%s\" for master, \"%s\" for master candidate,"
1359 " \"%s\" for regular, \"%s\" for drained, \"%s\" for offline" %
1361 fields.append((_MakeField("role", "Role", QFT_TEXT, role_doc), NQ_CONFIG, 0,
1362 lambda ctx, node: _GetNodeRole(node, ctx.master_uuid)))
1363 assert set(role_values) == constants.NR_ALL
1365 def _GetLength(getter):
1366 return lambda ctx, node: len(getter(ctx)[node.uuid])
1368 def _GetList(getter):
1369 return lambda ctx, node: utils.NiceSort(list(getter(ctx)[node.uuid]))
1371 # Add fields operating on instance lists
1372 for prefix, titleprefix, docword, getter in \
1373 [("p", "Pri", "primary", operator.attrgetter("node_to_primary")),
1374 ("s", "Sec", "secondary", operator.attrgetter("node_to_secondary"))]:
1375 # TODO: Allow filterting by hostname in list
1377 (_MakeField("%sinst_cnt" % prefix, "%sinst" % prefix.upper(), QFT_NUMBER,
1378 "Number of instances with this node as %s" % docword),
1379 NQ_INST, 0, _GetLength(getter)),
1380 (_MakeField("%sinst_list" % prefix, "%sInstances" % titleprefix,
1382 "List of instances with this node as %s" % docword),
1383 NQ_INST, 0, _GetList(getter)),
1388 (_MakeField(name, title, kind, doc), NQ_CONFIG, flags, _GetItemAttr(name))
1389 for (name, (title, kind, flags, doc)) in _NODE_SIMPLE_FIELDS.items()])
1391 # Add fields requiring live data
1393 (_MakeField(name, title, kind, doc), NQ_LIVE, 0,
1394 compat.partial(_GetLiveNodeField, nfield, kind))
1395 for (name, (title, kind, nfield, doc)) in _NODE_LIVE_FIELDS.items()])
1398 fields.extend(_GetItemTimestampFields(NQ_CONFIG))
1400 return _PrepareFieldList(fields, [])
1403 class InstanceQueryData:
1404 """Data container for instance data queries.
1407 def __init__(self, instances, cluster, disk_usage, offline_node_uuids,
1408 bad_node_uuids, live_data, wrongnode_inst, console, nodes,
1410 """Initializes this class.
1412 @param instances: List of instance objects
1413 @param cluster: Cluster object
1414 @type disk_usage: dict; instance name as key
1415 @param disk_usage: Per-instance disk usage
1416 @type offline_node_uuids: list of strings
1417 @param offline_node_uuids: List of offline nodes
1418 @type bad_node_uuids: list of strings
1419 @param bad_node_uuids: List of faulty nodes
1420 @type live_data: dict; instance name as key
1421 @param live_data: Per-instance live data
1422 @type wrongnode_inst: set
1423 @param wrongnode_inst: Set of instances running on wrong node(s)
1424 @type console: dict; instance name as key
1425 @param console: Per-instance console information
1426 @type nodes: dict; node UUID as key
1427 @param nodes: Node objects
1428 @type networks: dict; net_uuid as key
1429 @param networks: Network objects
1432 assert len(set(bad_node_uuids) & set(offline_node_uuids)) == \
1433 len(offline_node_uuids), \
1434 "Offline nodes not included in bad nodes"
1435 assert not (set(live_data.keys()) & set(bad_node_uuids)), \
1436 "Found live data for bad or offline nodes"
1438 self.instances = instances
1439 self.cluster = cluster
1440 self.disk_usage = disk_usage
1441 self.offline_nodes = offline_node_uuids
1442 self.bad_nodes = bad_node_uuids
1443 self.live_data = live_data
1444 self.wrongnode_inst = wrongnode_inst
1445 self.console = console
1447 self.groups = groups
1448 self.networks = networks
1450 # Used for individual rows
1451 self.inst_hvparams = None
1452 self.inst_beparams = None
1453 self.inst_osparams = None
1454 self.inst_nicparams = None
1457 """Iterate over all instances.
1459 This function has side-effects and only one instance of the resulting
1460 generator should be used at a time.
1463 for inst in self.instances:
1464 self.inst_hvparams = self.cluster.FillHV(inst, skip_globals=True)
1465 self.inst_beparams = self.cluster.FillBE(inst)
1466 self.inst_osparams = self.cluster.SimpleFillOS(inst.os, inst.osparams)
1467 self.inst_nicparams = [self.cluster.SimpleFillNIC(nic.nicparams)
1468 for nic in inst.nics]
1473 def _GetInstOperState(ctx, inst):
1474 """Get instance's operational status.
1476 @type ctx: L{InstanceQueryData}
1477 @type inst: L{objects.Instance}
1478 @param inst: Instance object
1481 # Can't use RS_OFFLINE here as it would describe the instance to
1482 # be offline when we actually don't know due to missing data
1483 if inst.primary_node in ctx.bad_nodes:
1486 return bool(ctx.live_data.get(inst.name))
1489 def _GetInstLiveData(name):
1490 """Build function for retrieving live data.
1493 @param name: Live data field name
1497 """Get live data for an instance.
1499 @type ctx: L{InstanceQueryData}
1500 @type inst: L{objects.Instance}
1501 @param inst: Instance object
1504 if (inst.primary_node in ctx.bad_nodes or
1505 inst.primary_node in ctx.offline_nodes):
1506 # Can't use RS_OFFLINE here as it would describe the instance to be
1507 # offline when we actually don't know due to missing data
1510 if inst.name in ctx.live_data:
1511 data = ctx.live_data[inst.name]
1520 def _GetInstStatus(ctx, inst):
1521 """Get instance status.
1523 @type ctx: L{InstanceQueryData}
1524 @type inst: L{objects.Instance}
1525 @param inst: Instance object
1528 if inst.primary_node in ctx.offline_nodes:
1529 return constants.INSTST_NODEOFFLINE
1531 if inst.primary_node in ctx.bad_nodes:
1532 return constants.INSTST_NODEDOWN
1534 if bool(ctx.live_data.get(inst.name)):
1535 if inst.name in ctx.wrongnode_inst:
1536 return constants.INSTST_WRONGNODE
1537 elif inst.admin_state == constants.ADMINST_UP:
1538 return constants.INSTST_RUNNING
1540 return constants.INSTST_ERRORUP
1542 if inst.admin_state == constants.ADMINST_UP:
1543 return constants.INSTST_ERRORDOWN
1544 elif inst.admin_state == constants.ADMINST_DOWN:
1545 return constants.INSTST_ADMINDOWN
1547 return constants.INSTST_ADMINOFFLINE
1550 def _GetInstDisk(index, cb):
1551 """Build function for calling another function with an instance Disk.
1554 @param index: Disk index
1560 """Call helper function with instance Disk.
1562 @type ctx: L{InstanceQueryData}
1563 @type inst: L{objects.Instance}
1564 @param inst: Instance object
1568 nic = inst.disks[index]
1572 return cb(ctx, index, nic)
1577 def _GetInstDiskSize(ctx, _, disk): # pylint: disable=W0613
1578 """Get a Disk's size.
1580 @type ctx: L{InstanceQueryData}
1581 @type disk: L{objects.Disk}
1582 @param disk: The Disk object
1585 if disk.size is None:
1591 def _GetInstDiskSpindles(ctx, _, disk): # pylint: disable=W0613
1592 """Get a Disk's spindles.
1594 @type disk: L{objects.Disk}
1595 @param disk: The Disk object
1598 if disk.spindles is None:
1601 return disk.spindles
1604 def _GetInstDeviceName(ctx, _, device): # pylint: disable=W0613
1605 """Get a Device's Name.
1607 @type ctx: L{InstanceQueryData}
1608 @type device: L{objects.NIC} or L{objects.Disk}
1609 @param device: The NIC or Disk object
1612 if device.name is None:
1618 def _GetInstDeviceUUID(ctx, _, device): # pylint: disable=W0613
1619 """Get a Device's UUID.
1621 @type ctx: L{InstanceQueryData}
1622 @type device: L{objects.NIC} or L{objects.Disk}
1623 @param device: The NIC or Disk object
1626 if device.uuid is None:
1632 def _GetInstNic(index, cb):
1633 """Build function for calling another function with an instance NIC.
1636 @param index: NIC index
1642 """Call helper function with instance NIC.
1644 @type ctx: L{InstanceQueryData}
1645 @type inst: L{objects.Instance}
1646 @param inst: Instance object
1650 nic = inst.nics[index]
1654 return cb(ctx, index, nic)
1659 def _GetInstNicNetworkName(ctx, _, nic): # pylint: disable=W0613
1660 """Get a NIC's Network.
1662 @type ctx: L{InstanceQueryData}
1663 @type nic: L{objects.NIC}
1664 @param nic: NIC object
1667 if nic.network is None:
1670 return ctx.networks[nic.network].name
1673 def _GetInstNicNetwork(ctx, _, nic): # pylint: disable=W0613
1674 """Get a NIC's Network.
1676 @type ctx: L{InstanceQueryData}
1677 @type nic: L{objects.NIC}
1678 @param nic: NIC object
1681 if nic.network is None:
1687 def _GetInstNicIp(ctx, _, nic): # pylint: disable=W0613
1688 """Get a NIC's IP address.
1690 @type ctx: L{InstanceQueryData}
1691 @type nic: L{objects.NIC}
1692 @param nic: NIC object
1701 def _GetInstNicBridge(ctx, index, _):
1702 """Get a NIC's bridge.
1704 @type ctx: L{InstanceQueryData}
1706 @param index: NIC index
1709 assert len(ctx.inst_nicparams) >= index
1711 nicparams = ctx.inst_nicparams[index]
1713 if nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1714 return nicparams[constants.NIC_LINK]
1719 def _GetInstAllNicNetworkNames(ctx, inst):
1720 """Get all network names for an instance.
1722 @type ctx: L{InstanceQueryData}
1723 @type inst: L{objects.Instance}
1724 @param inst: Instance object
1729 for nic in inst.nics:
1732 name = ctx.networks[nic.network].name
1735 assert len(result) == len(inst.nics)
1740 def _GetInstAllNicBridges(ctx, inst):
1741 """Get all network bridges for an instance.
1743 @type ctx: L{InstanceQueryData}
1744 @type inst: L{objects.Instance}
1745 @param inst: Instance object
1748 assert len(ctx.inst_nicparams) == len(inst.nics)
1752 for nicp in ctx.inst_nicparams:
1753 if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1754 result.append(nicp[constants.NIC_LINK])
1758 assert len(result) == len(inst.nics)
1763 def _GetInstNicParam(name):
1764 """Build function for retrieving a NIC parameter.
1767 @param name: Parameter name
1770 def fn(ctx, index, _):
1771 """Get a NIC's bridge.
1773 @type ctx: L{InstanceQueryData}
1774 @type inst: L{objects.Instance}
1775 @param inst: Instance object
1776 @type nic: L{objects.NIC}
1777 @param nic: NIC object
1780 assert len(ctx.inst_nicparams) >= index
1781 return ctx.inst_nicparams[index][name]
1786 def _GetInstanceNetworkFields():
1787 """Get instance fields involving network interfaces.
1789 @return: Tuple containing list of field definitions used as input for
1790 L{_PrepareFieldList} and a list of aliases
1793 nic_mac_fn = lambda ctx, _, nic: nic.mac
1794 nic_mode_fn = _GetInstNicParam(constants.NIC_MODE)
1795 nic_link_fn = _GetInstNicParam(constants.NIC_LINK)
1799 (_MakeField("nic.count", "NICs", QFT_NUMBER,
1800 "Number of network interfaces"),
1801 IQ_CONFIG, 0, lambda ctx, inst: len(inst.nics)),
1802 (_MakeField("nic.macs", "NIC_MACs", QFT_OTHER,
1803 "List containing each network interface's MAC address"),
1804 IQ_CONFIG, 0, lambda ctx, inst: [nic.mac for nic in inst.nics]),
1805 (_MakeField("nic.ips", "NIC_IPs", QFT_OTHER,
1806 "List containing each network interface's IP address"),
1807 IQ_CONFIG, 0, lambda ctx, inst: [nic.ip for nic in inst.nics]),
1808 (_MakeField("nic.names", "NIC_Names", QFT_OTHER,
1809 "List containing each network interface's name"),
1810 IQ_CONFIG, 0, lambda ctx, inst: [nic.name for nic in inst.nics]),
1811 (_MakeField("nic.uuids", "NIC_UUIDs", QFT_OTHER,
1812 "List containing each network interface's UUID"),
1813 IQ_CONFIG, 0, lambda ctx, inst: [nic.uuid for nic in inst.nics]),
1814 (_MakeField("nic.modes", "NIC_modes", QFT_OTHER,
1815 "List containing each network interface's mode"), IQ_CONFIG, 0,
1816 lambda ctx, inst: [nicp[constants.NIC_MODE]
1817 for nicp in ctx.inst_nicparams]),
1818 (_MakeField("nic.links", "NIC_links", QFT_OTHER,
1819 "List containing each network interface's link"), IQ_CONFIG, 0,
1820 lambda ctx, inst: [nicp[constants.NIC_LINK]
1821 for nicp in ctx.inst_nicparams]),
1822 (_MakeField("nic.bridges", "NIC_bridges", QFT_OTHER,
1823 "List containing each network interface's bridge"),
1824 IQ_CONFIG, 0, _GetInstAllNicBridges),
1825 (_MakeField("nic.networks", "NIC_networks", QFT_OTHER,
1826 "List containing each interface's network"), IQ_CONFIG, 0,
1827 lambda ctx, inst: [nic.network for nic in inst.nics]),
1828 (_MakeField("nic.networks.names", "NIC_networks_names", QFT_OTHER,
1829 "List containing each interface's network"),
1830 IQ_NETWORKS, 0, _GetInstAllNicNetworkNames)
1834 for i in range(constants.MAX_NICS):
1835 numtext = utils.FormatOrdinal(i + 1)
1837 (_MakeField("nic.ip/%s" % i, "NicIP/%s" % i, QFT_TEXT,
1838 "IP address of %s network interface" % numtext),
1839 IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicIp)),
1840 (_MakeField("nic.mac/%s" % i, "NicMAC/%s" % i, QFT_TEXT,
1841 "MAC address of %s network interface" % numtext),
1842 IQ_CONFIG, 0, _GetInstNic(i, nic_mac_fn)),
1843 (_MakeField("nic.name/%s" % i, "NicName/%s" % i, QFT_TEXT,
1844 "Name address of %s network interface" % numtext),
1845 IQ_CONFIG, 0, _GetInstNic(i, _GetInstDeviceName)),
1846 (_MakeField("nic.uuid/%s" % i, "NicUUID/%s" % i, QFT_TEXT,
1847 "UUID address of %s network interface" % numtext),
1848 IQ_CONFIG, 0, _GetInstNic(i, _GetInstDeviceUUID)),
1849 (_MakeField("nic.mode/%s" % i, "NicMode/%s" % i, QFT_TEXT,
1850 "Mode of %s network interface" % numtext),
1851 IQ_CONFIG, 0, _GetInstNic(i, nic_mode_fn)),
1852 (_MakeField("nic.link/%s" % i, "NicLink/%s" % i, QFT_TEXT,
1853 "Link of %s network interface" % numtext),
1854 IQ_CONFIG, 0, _GetInstNic(i, nic_link_fn)),
1855 (_MakeField("nic.bridge/%s" % i, "NicBridge/%s" % i, QFT_TEXT,
1856 "Bridge of %s network interface" % numtext),
1857 IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicBridge)),
1858 (_MakeField("nic.network/%s" % i, "NicNetwork/%s" % i, QFT_TEXT,
1859 "Network of %s network interface" % numtext),
1860 IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicNetwork)),
1861 (_MakeField("nic.network.name/%s" % i, "NicNetworkName/%s" % i, QFT_TEXT,
1862 "Network name of %s network interface" % numtext),
1863 IQ_NETWORKS, 0, _GetInstNic(i, _GetInstNicNetworkName)),
1867 # Legacy fields for first NIC
1869 ("mac", "nic.mac/0"),
1870 ("bridge", "nic.bridge/0"),
1871 ("nic_mode", "nic.mode/0"),
1872 ("nic_link", "nic.link/0"),
1873 ("nic_network", "nic.network/0"),
1876 return (fields, aliases)
1879 def _GetInstDiskUsage(ctx, inst):
1880 """Get disk usage for an instance.
1882 @type ctx: L{InstanceQueryData}
1883 @type inst: L{objects.Instance}
1884 @param inst: Instance object
1887 usage = ctx.disk_usage[inst.name]
1895 def _GetInstanceConsole(ctx, inst):
1896 """Get console information for instance.
1898 @type ctx: L{InstanceQueryData}
1899 @type inst: L{objects.Instance}
1900 @param inst: Instance object
1903 consinfo = ctx.console[inst.name]
1905 if consinfo is None:
1911 def _GetInstanceDiskFields():
1912 """Get instance fields involving disks.
1914 @return: List of field definitions used as input for L{_PrepareFieldList}
1918 (_MakeField("disk_usage", "DiskUsage", QFT_UNIT,
1919 "Total disk space used by instance on each of its nodes;"
1920 " this is not the disk size visible to the instance, but"
1921 " the usage on the node"),
1922 IQ_DISKUSAGE, 0, _GetInstDiskUsage),
1923 (_MakeField("disk.count", "Disks", QFT_NUMBER, "Number of disks"),
1924 IQ_CONFIG, 0, lambda ctx, inst: len(inst.disks)),
1925 (_MakeField("disk.sizes", "Disk_sizes", QFT_OTHER, "List of disk sizes"),
1926 IQ_CONFIG, 0, lambda ctx, inst: [disk.size for disk in inst.disks]),
1927 (_MakeField("disk.spindles", "Disk_spindles", QFT_OTHER,
1928 "List of disk spindles"),
1929 IQ_CONFIG, 0, lambda ctx, inst: [disk.spindles for disk in inst.disks]),
1930 (_MakeField("disk.names", "Disk_names", QFT_OTHER, "List of disk names"),
1931 IQ_CONFIG, 0, lambda ctx, inst: [disk.name for disk in inst.disks]),
1932 (_MakeField("disk.uuids", "Disk_UUIDs", QFT_OTHER, "List of disk UUIDs"),
1933 IQ_CONFIG, 0, lambda ctx, inst: [disk.uuid for disk in inst.disks]),
1937 for i in range(constants.MAX_DISKS):
1938 numtext = utils.FormatOrdinal(i + 1)
1940 (_MakeField("disk.size/%s" % i, "Disk/%s" % i, QFT_UNIT,
1941 "Disk size of %s disk" % numtext),
1942 IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDiskSize)),
1943 (_MakeField("disk.spindles/%s" % i, "DiskSpindles/%s" % i, QFT_NUMBER,
1944 "Spindles of %s disk" % numtext),
1945 IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDiskSpindles)),
1946 (_MakeField("disk.name/%s" % i, "DiskName/%s" % i, QFT_TEXT,
1947 "Name of %s disk" % numtext),
1948 IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDeviceName)),
1949 (_MakeField("disk.uuid/%s" % i, "DiskUUID/%s" % i, QFT_TEXT,
1950 "UUID of %s disk" % numtext),
1951 IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDeviceUUID))])
1956 def _GetInstanceParameterFields():
1957 """Get instance fields involving parameters.
1959 @return: List of field definitions used as input for L{_PrepareFieldList}
1964 (_MakeField("hvparams", "HypervisorParameters", QFT_OTHER,
1965 "Hypervisor parameters (merged)"),
1966 IQ_CONFIG, 0, lambda ctx, _: ctx.inst_hvparams),
1967 (_MakeField("beparams", "BackendParameters", QFT_OTHER,
1968 "Backend parameters (merged)"),
1969 IQ_CONFIG, 0, lambda ctx, _: ctx.inst_beparams),
1970 (_MakeField("osparams", "OpSysParameters", QFT_OTHER,
1971 "Operating system parameters (merged)"),
1972 IQ_CONFIG, 0, lambda ctx, _: ctx.inst_osparams),
1974 # Unfilled parameters
1975 (_MakeField("custom_hvparams", "CustomHypervisorParameters", QFT_OTHER,
1976 "Custom hypervisor parameters"),
1977 IQ_CONFIG, 0, _GetItemAttr("hvparams")),
1978 (_MakeField("custom_beparams", "CustomBackendParameters", QFT_OTHER,
1979 "Custom backend parameters",),
1980 IQ_CONFIG, 0, _GetItemAttr("beparams")),
1981 (_MakeField("custom_osparams", "CustomOpSysParameters", QFT_OTHER,
1982 "Custom operating system parameters",),
1983 IQ_CONFIG, 0, _GetItemAttr("osparams")),
1984 (_MakeField("custom_nicparams", "CustomNicParameters", QFT_OTHER,
1985 "Custom network interface parameters"),
1986 IQ_CONFIG, 0, lambda ctx, inst: [nic.nicparams for nic in inst.nics]),
1990 def _GetInstHvParam(name):
1991 return lambda ctx, _: ctx.inst_hvparams.get(name, _FS_UNAVAIL)
1994 (_MakeField("hv/%s" % name,
1995 constants.HVS_PARAMETER_TITLES.get(name, "hv/%s" % name),
1996 _VTToQFT[kind], "The \"%s\" hypervisor parameter" % name),
1997 IQ_CONFIG, 0, _GetInstHvParam(name))
1998 for name, kind in constants.HVS_PARAMETER_TYPES.items()
1999 if name not in constants.HVC_GLOBALS])
2002 def _GetInstBeParam(name):
2003 return lambda ctx, _: ctx.inst_beparams.get(name, None)
2006 (_MakeField("be/%s" % name,
2007 constants.BES_PARAMETER_TITLES.get(name, "be/%s" % name),
2008 _VTToQFT[kind], "The \"%s\" backend parameter" % name),
2009 IQ_CONFIG, 0, _GetInstBeParam(name))
2010 for name, kind in constants.BES_PARAMETER_TYPES.items()])
2015 _INST_SIMPLE_FIELDS = {
2016 "disk_template": ("Disk_template", QFT_TEXT, 0, "Instance disk template"),
2017 "hypervisor": ("Hypervisor", QFT_TEXT, 0, "Hypervisor name"),
2018 "name": ("Instance", QFT_TEXT, QFF_HOSTNAME, "Instance name"),
2019 # Depending on the hypervisor, the port can be None
2020 "network_port": ("Network_port", QFT_OTHER, 0,
2021 "Instance network port if available (e.g. for VNC console)"),
2022 "os": ("OS", QFT_TEXT, 0, "Operating system"),
2023 "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Instance"),
2024 "uuid": ("UUID", QFT_TEXT, 0, "Instance UUID"),
2028 def _GetNodeName(ctx, default, node_uuid):
2029 """Gets node name of a node.
2031 @type ctx: L{InstanceQueryData}
2032 @param default: Default value
2033 @type node_uuid: string
2034 @param node_uuid: Node UUID
2038 node = ctx.nodes[node_uuid]
2045 def _GetInstNodeGroup(ctx, default, node_uuid):
2046 """Gets group UUID of an instance node.
2048 @type ctx: L{InstanceQueryData}
2049 @param default: Default value
2050 @type node_uuid: string
2051 @param node_uuid: Node UUID
2055 node = ctx.nodes[node_uuid]
2062 def _GetInstNodeGroupName(ctx, default, node_uuid):
2063 """Gets group name of an instance node.
2065 @type ctx: L{InstanceQueryData}
2066 @param default: Default value
2067 @type node_uuid: string
2068 @param node_uuid: Node UUID
2072 node = ctx.nodes[node_uuid]
2077 group = ctx.groups[node.group]
2084 def _BuildInstanceFields():
2085 """Builds list of fields for instance queries.
2089 (_MakeField("pnode", "Primary_node", QFT_TEXT, "Primary node"),
2090 IQ_NODES, QFF_HOSTNAME,
2091 lambda ctx, inst: _GetNodeName(ctx, None, inst.primary_node)),
2092 (_MakeField("pnode.group", "PrimaryNodeGroup", QFT_TEXT,
2093 "Primary node's group"),
2095 lambda ctx, inst: _GetInstNodeGroupName(ctx, _FS_UNAVAIL,
2096 inst.primary_node)),
2097 (_MakeField("pnode.group.uuid", "PrimaryNodeGroupUUID", QFT_TEXT,
2098 "Primary node's group UUID"),
2100 lambda ctx, inst: _GetInstNodeGroup(ctx, _FS_UNAVAIL, inst.primary_node)),
2101 # TODO: Allow filtering by secondary node as hostname
2102 (_MakeField("snodes", "Secondary_Nodes", QFT_OTHER,
2103 "Secondary nodes; usually this will just be one node"),
2105 lambda ctx, inst: map(compat.partial(_GetNodeName, ctx, None),
2106 inst.secondary_nodes)),
2107 (_MakeField("snodes.group", "SecondaryNodesGroups", QFT_OTHER,
2108 "Node groups of secondary nodes"),
2110 lambda ctx, inst: map(compat.partial(_GetInstNodeGroupName, ctx, None),
2111 inst.secondary_nodes)),
2112 (_MakeField("snodes.group.uuid", "SecondaryNodesGroupsUUID", QFT_OTHER,
2113 "Node group UUIDs of secondary nodes"),
2115 lambda ctx, inst: map(compat.partial(_GetInstNodeGroup, ctx, None),
2116 inst.secondary_nodes)),
2117 (_MakeField("admin_state", "InstanceState", QFT_TEXT,
2118 "Desired state of instance"),
2119 IQ_CONFIG, 0, _GetItemAttr("admin_state")),
2120 (_MakeField("admin_up", "Autostart", QFT_BOOL,
2121 "Desired state of instance"),
2122 IQ_CONFIG, 0, lambda ctx, inst: inst.admin_state == constants.ADMINST_UP),
2123 (_MakeField("disks_active", "DisksActive", QFT_BOOL,
2124 "Desired state of instance disks"),
2125 IQ_CONFIG, 0, _GetItemAttr("disks_active")),
2126 (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, 0,
2127 lambda ctx, inst: list(inst.GetTags())),
2128 (_MakeField("console", "Console", QFT_OTHER,
2129 "Instance console information"), IQ_CONSOLE, 0,
2130 _GetInstanceConsole),
2135 (_MakeField(name, title, kind, doc), IQ_CONFIG, flags, _GetItemAttr(name))
2136 for (name, (title, kind, flags, doc)) in _INST_SIMPLE_FIELDS.items()])
2138 # Fields requiring talking to the node
2140 (_MakeField("oper_state", "Running", QFT_BOOL, "Actual state of instance"),
2141 IQ_LIVE, 0, _GetInstOperState),
2142 (_MakeField("oper_ram", "Memory", QFT_UNIT,
2143 "Actual memory usage as seen by hypervisor"),
2144 IQ_LIVE, 0, _GetInstLiveData("memory")),
2145 (_MakeField("oper_vcpus", "VCPUs", QFT_NUMBER,
2146 "Actual number of VCPUs as seen by hypervisor"),
2147 IQ_LIVE, 0, _GetInstLiveData("vcpus")),
2151 status_values = (constants.INSTST_RUNNING, constants.INSTST_ADMINDOWN,
2152 constants.INSTST_WRONGNODE, constants.INSTST_ERRORUP,
2153 constants.INSTST_ERRORDOWN, constants.INSTST_NODEDOWN,
2154 constants.INSTST_NODEOFFLINE, constants.INSTST_ADMINOFFLINE)
2155 status_doc = ("Instance status; \"%s\" if instance is set to be running"
2156 " and actually is, \"%s\" if instance is stopped and"
2157 " is not running, \"%s\" if instance running, but not on its"
2158 " designated primary node, \"%s\" if instance should be"
2159 " stopped, but is actually running, \"%s\" if instance should"
2160 " run, but doesn't, \"%s\" if instance's primary node is down,"
2161 " \"%s\" if instance's primary node is marked offline,"
2162 " \"%s\" if instance is offline and does not use dynamic"
2163 " resources" % status_values)
2164 fields.append((_MakeField("status", "Status", QFT_TEXT, status_doc),
2165 IQ_LIVE, 0, _GetInstStatus))
2166 assert set(status_values) == constants.INSTST_ALL, \
2167 "Status documentation mismatch"
2169 (network_fields, network_aliases) = _GetInstanceNetworkFields()
2171 fields.extend(network_fields)
2172 fields.extend(_GetInstanceParameterFields())
2173 fields.extend(_GetInstanceDiskFields())
2174 fields.extend(_GetItemTimestampFields(IQ_CONFIG))
2177 ("vcpus", "be/vcpus"),
2178 ("be/memory", "be/maxmem"),
2179 ("sda_size", "disk.size/0"),
2180 ("sdb_size", "disk.size/1"),
2183 return _PrepareFieldList(fields, aliases)
2186 class LockQueryData:
2187 """Data container for lock data queries.
2190 def __init__(self, lockdata):
2191 """Initializes this class.
2194 self.lockdata = lockdata
2197 """Iterate over all locks.
2200 return iter(self.lockdata)
2203 def _GetLockOwners(_, data):
2204 """Returns a sorted list of a lock's current owners.
2207 (_, _, owners, _) = data
2210 owners = utils.NiceSort(owners)
2215 def _GetLockPending(_, data):
2216 """Returns a sorted list of a lock's pending acquires.
2219 (_, _, _, pending) = data
2222 pending = [(mode, utils.NiceSort(names))
2223 for (mode, names) in pending]
2228 def _BuildLockFields():
2229 """Builds list of fields for lock queries.
2232 return _PrepareFieldList([
2233 # TODO: Lock names are not always hostnames. Should QFF_HOSTNAME be used?
2234 (_MakeField("name", "Name", QFT_TEXT, "Lock name"), None, 0,
2235 lambda ctx, (name, mode, owners, pending): name),
2236 (_MakeField("mode", "Mode", QFT_OTHER,
2237 "Mode in which the lock is currently acquired"
2238 " (exclusive or shared)"),
2239 LQ_MODE, 0, lambda ctx, (name, mode, owners, pending): mode),
2240 (_MakeField("owner", "Owner", QFT_OTHER, "Current lock owner(s)"),
2241 LQ_OWNER, 0, _GetLockOwners),
2242 (_MakeField("pending", "Pending", QFT_OTHER,
2243 "Threads waiting for the lock"),
2244 LQ_PENDING, 0, _GetLockPending),
2248 class GroupQueryData:
2249 """Data container for node group data queries.
2252 def __init__(self, cluster, groups, group_to_nodes, group_to_instances,
2254 """Initializes this class.
2256 @param cluster: Cluster object
2257 @param groups: List of node group objects
2258 @type group_to_nodes: dict; group UUID as key
2259 @param group_to_nodes: Per-group list of nodes
2260 @type group_to_instances: dict; group UUID as key
2261 @param group_to_instances: Per-group list of (primary) instances
2262 @type want_diskparams: bool
2263 @param want_diskparams: Whether diskparamters should be calculated
2266 self.groups = groups
2267 self.group_to_nodes = group_to_nodes
2268 self.group_to_instances = group_to_instances
2269 self.cluster = cluster
2270 self.want_diskparams = want_diskparams
2272 # Used for individual rows
2273 self.group_ipolicy = None
2274 self.ndparams = None
2275 self.group_dp = None
2278 """Iterate over all node groups.
2280 This function has side-effects and only one instance of the resulting
2281 generator should be used at a time.
2284 for group in self.groups:
2285 self.group_ipolicy = self.cluster.SimpleFillIPolicy(group.ipolicy)
2286 self.ndparams = self.cluster.SimpleFillND(group.ndparams)
2287 if self.want_diskparams:
2288 self.group_dp = self.cluster.SimpleFillDP(group.diskparams)
2290 self.group_dp = None
2294 _GROUP_SIMPLE_FIELDS = {
2295 "alloc_policy": ("AllocPolicy", QFT_TEXT, "Allocation policy for group"),
2296 "name": ("Group", QFT_TEXT, "Group name"),
2297 "serial_no": ("SerialNo", QFT_NUMBER, _SERIAL_NO_DOC % "Group"),
2298 "uuid": ("UUID", QFT_TEXT, "Group UUID"),
2302 def _BuildGroupFields():
2303 """Builds list of fields for node group queries.
2307 fields = [(_MakeField(name, title, kind, doc), GQ_CONFIG, 0,
2309 for (name, (title, kind, doc)) in _GROUP_SIMPLE_FIELDS.items()]
2311 def _GetLength(getter):
2312 return lambda ctx, group: len(getter(ctx)[group.uuid])
2314 def _GetSortedList(getter):
2315 return lambda ctx, group: utils.NiceSort(getter(ctx)[group.uuid])
2317 group_to_nodes = operator.attrgetter("group_to_nodes")
2318 group_to_instances = operator.attrgetter("group_to_instances")
2320 # Add fields for nodes
2322 (_MakeField("node_cnt", "Nodes", QFT_NUMBER, "Number of nodes"),
2323 GQ_NODE, 0, _GetLength(group_to_nodes)),
2324 (_MakeField("node_list", "NodeList", QFT_OTHER, "List of nodes"),
2325 GQ_NODE, 0, _GetSortedList(group_to_nodes)),
2328 # Add fields for instances
2330 (_MakeField("pinst_cnt", "Instances", QFT_NUMBER,
2331 "Number of primary instances"),
2332 GQ_INST, 0, _GetLength(group_to_instances)),
2333 (_MakeField("pinst_list", "InstanceList", QFT_OTHER,
2334 "List of primary instances"),
2335 GQ_INST, 0, _GetSortedList(group_to_instances)),
2340 (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), GQ_CONFIG, 0,
2341 lambda ctx, group: list(group.GetTags())),
2342 (_MakeField("ipolicy", "InstancePolicy", QFT_OTHER,
2343 "Instance policy limitations (merged)"),
2344 GQ_CONFIG, 0, lambda ctx, _: ctx.group_ipolicy),
2345 (_MakeField("custom_ipolicy", "CustomInstancePolicy", QFT_OTHER,
2346 "Custom instance policy limitations"),
2347 GQ_CONFIG, 0, _GetItemAttr("ipolicy")),
2348 (_MakeField("custom_ndparams", "CustomNDParams", QFT_OTHER,
2349 "Custom node parameters"),
2350 GQ_CONFIG, 0, _GetItemAttr("ndparams")),
2351 (_MakeField("ndparams", "NDParams", QFT_OTHER,
2353 GQ_CONFIG, 0, lambda ctx, _: ctx.ndparams),
2354 (_MakeField("diskparams", "DiskParameters", QFT_OTHER,
2355 "Disk parameters (merged)"),
2356 GQ_DISKPARAMS, 0, lambda ctx, _: ctx.group_dp),
2357 (_MakeField("custom_diskparams", "CustomDiskParameters", QFT_OTHER,
2358 "Custom disk parameters"),
2359 GQ_CONFIG, 0, _GetItemAttr("diskparams")),
2363 fields.extend(_BuildNDFields(True))
2365 fields.extend(_GetItemTimestampFields(GQ_CONFIG))
2367 return _PrepareFieldList(fields, [])
2370 class OsInfo(objects.ConfigObject):
2383 def _BuildOsFields():
2384 """Builds list of fields for operating system queries.
2388 (_MakeField("name", "Name", QFT_TEXT, "Operating system name"),
2389 None, 0, _GetItemAttr("name")),
2390 (_MakeField("valid", "Valid", QFT_BOOL,
2391 "Whether operating system definition is valid"),
2392 None, 0, _GetItemAttr("valid")),
2393 (_MakeField("hidden", "Hidden", QFT_BOOL,
2394 "Whether operating system is hidden"),
2395 None, 0, _GetItemAttr("hidden")),
2396 (_MakeField("blacklisted", "Blacklisted", QFT_BOOL,
2397 "Whether operating system is blacklisted"),
2398 None, 0, _GetItemAttr("blacklisted")),
2399 (_MakeField("variants", "Variants", QFT_OTHER,
2400 "Operating system variants"),
2401 None, 0, _ConvWrap(utils.NiceSort, _GetItemAttr("variants"))),
2402 (_MakeField("api_versions", "ApiVersions", QFT_OTHER,
2403 "Operating system API versions"),
2404 None, 0, _ConvWrap(sorted, _GetItemAttr("api_versions"))),
2405 (_MakeField("parameters", "Parameters", QFT_OTHER,
2406 "Operating system parameters"),
2407 None, 0, _ConvWrap(compat.partial(utils.NiceSort, key=compat.fst),
2408 _GetItemAttr("parameters"))),
2409 (_MakeField("node_status", "NodeStatus", QFT_OTHER,
2410 "Status from node"),
2411 None, 0, _GetItemAttr("node_status")),
2414 return _PrepareFieldList(fields, [])
2417 class ExtStorageInfo(objects.ConfigObject):
2426 def _BuildExtStorageFields():
2427 """Builds list of fields for extstorage provider queries.
2431 (_MakeField("name", "Name", QFT_TEXT, "ExtStorage provider name"),
2432 None, 0, _GetItemAttr("name")),
2433 (_MakeField("node_status", "NodeStatus", QFT_OTHER,
2434 "Status from node"),
2435 None, 0, _GetItemAttr("node_status")),
2436 (_MakeField("nodegroup_status", "NodegroupStatus", QFT_OTHER,
2437 "Overall Nodegroup status"),
2438 None, 0, _GetItemAttr("nodegroup_status")),
2439 (_MakeField("parameters", "Parameters", QFT_OTHER,
2440 "ExtStorage provider parameters"),
2441 None, 0, _GetItemAttr("parameters")),
2444 return _PrepareFieldList(fields, [])
2447 def _JobUnavailInner(fn, ctx, (job_id, job)): # pylint: disable=W0613
2448 """Return L{_FS_UNAVAIL} if job is None.
2450 When listing specifc jobs (e.g. "gnt-job list 1 2 3"), a job may not be
2451 found, in which case this function converts it to L{_FS_UNAVAIL}.
2460 def _JobUnavail(inner):
2461 """Wrapper for L{_JobUnavailInner}.
2464 return compat.partial(_JobUnavailInner, inner)
2467 def _PerJobOpInner(fn, job):
2468 """Executes a function per opcode in a job.
2471 return map(fn, job.ops)
2475 """Wrapper for L{_PerJobOpInner}.
2478 return _JobUnavail(compat.partial(_PerJobOpInner, fn))
2481 def _JobTimestampInner(fn, job):
2482 """Converts unavailable timestamp to L{_FS_UNAVAIL}.
2487 if timestamp is None:
2493 def _JobTimestamp(fn):
2494 """Wrapper for L{_JobTimestampInner}.
2497 return _JobUnavail(compat.partial(_JobTimestampInner, fn))
2500 def _BuildJobFields():
2501 """Builds list of fields for job queries.
2505 (_MakeField("id", "ID", QFT_NUMBER, "Job ID"),
2506 None, QFF_JOB_ID, lambda _, (job_id, job): job_id),
2507 (_MakeField("status", "Status", QFT_TEXT, "Job status"),
2508 None, 0, _JobUnavail(lambda job: job.CalcStatus())),
2509 (_MakeField("priority", "Priority", QFT_NUMBER,
2510 ("Current job priority (%s to %s)" %
2511 (constants.OP_PRIO_LOWEST, constants.OP_PRIO_HIGHEST))),
2512 None, 0, _JobUnavail(lambda job: job.CalcPriority())),
2513 (_MakeField("archived", "Archived", QFT_BOOL, "Whether job is archived"),
2514 JQ_ARCHIVED, 0, lambda _, (job_id, job): job.archived),
2515 (_MakeField("ops", "OpCodes", QFT_OTHER, "List of all opcodes"),
2516 None, 0, _PerJobOp(lambda op: op.input.__getstate__())),
2517 (_MakeField("opresult", "OpCode_result", QFT_OTHER,
2518 "List of opcodes results"),
2519 None, 0, _PerJobOp(operator.attrgetter("result"))),
2520 (_MakeField("opstatus", "OpCode_status", QFT_OTHER,
2521 "List of opcodes status"),
2522 None, 0, _PerJobOp(operator.attrgetter("status"))),
2523 (_MakeField("oplog", "OpCode_log", QFT_OTHER,
2524 "List of opcode output logs"),
2525 None, 0, _PerJobOp(operator.attrgetter("log"))),
2526 (_MakeField("opstart", "OpCode_start", QFT_OTHER,
2527 "List of opcode start timestamps (before acquiring locks)"),
2528 None, 0, _PerJobOp(operator.attrgetter("start_timestamp"))),
2529 (_MakeField("opexec", "OpCode_exec", QFT_OTHER,
2530 "List of opcode execution start timestamps (after acquiring"
2532 None, 0, _PerJobOp(operator.attrgetter("exec_timestamp"))),
2533 (_MakeField("opend", "OpCode_end", QFT_OTHER,
2534 "List of opcode execution end timestamps"),
2535 None, 0, _PerJobOp(operator.attrgetter("end_timestamp"))),
2536 (_MakeField("oppriority", "OpCode_prio", QFT_OTHER,
2537 "List of opcode priorities"),
2538 None, 0, _PerJobOp(operator.attrgetter("priority"))),
2539 (_MakeField("summary", "Summary", QFT_OTHER,
2540 "List of per-opcode summaries"),
2541 None, 0, _PerJobOp(lambda op: op.input.Summary())),
2545 for (name, attr, title, desc) in [
2546 ("received_ts", "received_timestamp", "Received",
2547 "Timestamp of when job was received"),
2548 ("start_ts", "start_timestamp", "Start", "Timestamp of job start"),
2549 ("end_ts", "end_timestamp", "End", "Timestamp of job end"),
2551 getter = operator.attrgetter(attr)
2553 (_MakeField(name, title, QFT_OTHER,
2554 "%s (tuple containing seconds and microseconds)" % desc),
2555 None, QFF_SPLIT_TIMESTAMP, _JobTimestamp(getter)),
2558 return _PrepareFieldList(fields, [])
2561 def _GetExportName(_, (node_name, expname)): # pylint: disable=W0613
2562 """Returns an export name if available.
2571 def _BuildExportFields():
2572 """Builds list of fields for exports.
2576 (_MakeField("node", "Node", QFT_TEXT, "Node name"),
2577 None, QFF_HOSTNAME, lambda _, (node_name, expname): node_name),
2578 (_MakeField("export", "Export", QFT_TEXT, "Export name"),
2579 None, 0, _GetExportName),
2582 return _PrepareFieldList(fields, [])
2585 _CLUSTER_VERSION_FIELDS = {
2586 "software_version": ("SoftwareVersion", QFT_TEXT, constants.RELEASE_VERSION,
2587 "Software version"),
2588 "protocol_version": ("ProtocolVersion", QFT_NUMBER,
2589 constants.PROTOCOL_VERSION,
2590 "RPC protocol version"),
2591 "config_version": ("ConfigVersion", QFT_NUMBER, constants.CONFIG_VERSION,
2592 "Configuration format version"),
2593 "os_api_version": ("OsApiVersion", QFT_NUMBER, max(constants.OS_API_VERSIONS),
2594 "API version for OS template scripts"),
2595 "export_version": ("ExportVersion", QFT_NUMBER, constants.EXPORT_VERSION,
2596 "Import/export file format version"),
2600 _CLUSTER_SIMPLE_FIELDS = {
2601 "cluster_name": ("Name", QFT_TEXT, QFF_HOSTNAME, "Cluster name"),
2602 "volume_group_name": ("VgName", QFT_TEXT, 0, "LVM volume group name"),
2606 class ClusterQueryData:
2607 def __init__(self, cluster, nodes, drain_flag, watcher_pause):
2608 """Initializes this class.
2610 @type cluster: L{objects.Cluster}
2611 @param cluster: Instance of cluster object
2612 @type nodes: dict; node UUID as key
2613 @param nodes: Node objects
2614 @type drain_flag: bool
2615 @param drain_flag: Whether job queue is drained
2616 @type watcher_pause: number
2617 @param watcher_pause: Until when watcher is paused (Unix timestamp)
2620 self._cluster = cluster
2622 self.drain_flag = drain_flag
2623 self.watcher_pause = watcher_pause
2626 return iter([self._cluster])
2629 def _ClusterWatcherPause(ctx, _):
2630 """Returns until when watcher is paused (if available).
2633 if ctx.watcher_pause is None:
2636 return ctx.watcher_pause
2639 def _BuildClusterFields():
2640 """Builds list of fields for cluster information.
2644 (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), CQ_CONFIG, 0,
2645 lambda ctx, cluster: list(cluster.GetTags())),
2646 (_MakeField("architecture", "ArchInfo", QFT_OTHER,
2647 "Architecture information"), None, 0,
2648 lambda ctx, _: runtime.GetArchInfo()),
2649 (_MakeField("drain_flag", "QueueDrained", QFT_BOOL,
2650 "Flag whether job queue is drained"), CQ_QUEUE_DRAINED, 0,
2651 lambda ctx, _: ctx.drain_flag),
2652 (_MakeField("watcher_pause", "WatcherPause", QFT_TIMESTAMP,
2653 "Until when watcher is paused"), CQ_WATCHER_PAUSE, 0,
2654 _ClusterWatcherPause),
2655 (_MakeField("master_node", "Master", QFT_TEXT, "Master node name"),
2656 CQ_CONFIG, QFF_HOSTNAME,
2657 lambda ctx, cluster: _GetNodeName(ctx, None, cluster.master_node)),
2662 (_MakeField(name, title, kind, doc), CQ_CONFIG, flags, _GetItemAttr(name))
2663 for (name, (title, kind, flags, doc)) in _CLUSTER_SIMPLE_FIELDS.items()
2668 (_MakeField(name, title, kind, doc), None, 0, _StaticValue(value))
2669 for (name, (title, kind, value, doc)) in _CLUSTER_VERSION_FIELDS.items()])
2672 fields.extend(_GetItemTimestampFields(CQ_CONFIG))
2674 return _PrepareFieldList(fields, [
2675 ("name", "cluster_name")])
2678 class NetworkQueryData:
2679 """Data container for network data queries.
2682 def __init__(self, networks, network_to_groups,
2683 network_to_instances, stats):
2684 """Initializes this class.
2686 @param networks: List of network objects
2687 @type network_to_groups: dict; network UUID as key
2688 @param network_to_groups: Per-network list of groups
2689 @type network_to_instances: dict; network UUID as key
2690 @param network_to_instances: Per-network list of instances
2691 @type stats: dict; network UUID as key
2692 @param stats: Per-network usage statistics
2695 self.networks = networks
2696 self.network_to_groups = network_to_groups
2697 self.network_to_instances = network_to_instances
2701 """Iterate over all networks.
2704 for net in self.networks:
2706 self.curstats = self.stats.get(net.uuid, None)
2708 self.curstats = None
2712 _NETWORK_SIMPLE_FIELDS = {
2713 "name": ("Network", QFT_TEXT, 0, "Name"),
2714 "network": ("Subnet", QFT_TEXT, 0, "IPv4 subnet"),
2715 "gateway": ("Gateway", QFT_OTHER, 0, "IPv4 gateway"),
2716 "network6": ("IPv6Subnet", QFT_OTHER, 0, "IPv6 subnet"),
2717 "gateway6": ("IPv6Gateway", QFT_OTHER, 0, "IPv6 gateway"),
2718 "mac_prefix": ("MacPrefix", QFT_OTHER, 0, "MAC address prefix"),
2719 "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Network"),
2720 "uuid": ("UUID", QFT_TEXT, 0, "Network UUID"),
2724 _NETWORK_STATS_FIELDS = {
2725 "free_count": ("FreeCount", QFT_NUMBER, 0, "Number of available addresses"),
2727 ("ReservedCount", QFT_NUMBER, 0, "Number of reserved addresses"),
2728 "map": ("Map", QFT_TEXT, 0, "Actual mapping"),
2729 "external_reservations":
2730 ("ExternalReservations", QFT_TEXT, 0, "External reservations"),
2734 def _GetNetworkStatsField(field, kind, ctx, _):
2735 """Gets the value of a "stats" field from L{NetworkQueryData}.
2737 @param field: Field name
2738 @param kind: Data kind, one of L{constants.QFT_ALL}
2739 @type ctx: L{NetworkQueryData}
2742 return _GetStatsField(field, kind, ctx.curstats)
2745 def _BuildNetworkFields():
2746 """Builds list of fields for network queries.
2750 (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, 0,
2751 lambda ctx, inst: list(inst.GetTags())),
2756 (_MakeField(name, title, kind, doc),
2757 NETQ_CONFIG, 0, _GetItemMaybeAttr(name))
2758 for (name, (title, kind, _, doc)) in _NETWORK_SIMPLE_FIELDS.items()])
2760 def _GetLength(getter):
2761 return lambda ctx, network: len(getter(ctx)[network.uuid])
2763 def _GetSortedList(getter):
2764 return lambda ctx, network: utils.NiceSort(getter(ctx)[network.uuid])
2766 network_to_groups = operator.attrgetter("network_to_groups")
2767 network_to_instances = operator.attrgetter("network_to_instances")
2769 # Add fields for node groups
2771 (_MakeField("group_cnt", "NodeGroups", QFT_NUMBER, "Number of nodegroups"),
2772 NETQ_GROUP, 0, _GetLength(network_to_groups)),
2773 (_MakeField("group_list", "GroupList", QFT_OTHER,
2774 "List of nodegroups (group name, NIC mode, NIC link)"),
2775 NETQ_GROUP, 0, lambda ctx, network: network_to_groups(ctx)[network.uuid]),
2778 # Add fields for instances
2780 (_MakeField("inst_cnt", "Instances", QFT_NUMBER, "Number of instances"),
2781 NETQ_INST, 0, _GetLength(network_to_instances)),
2782 (_MakeField("inst_list", "InstanceList", QFT_OTHER, "List of instances"),
2783 NETQ_INST, 0, _GetSortedList(network_to_instances)),
2786 # Add fields for usage statistics
2788 (_MakeField(name, title, kind, doc), NETQ_STATS, 0,
2789 compat.partial(_GetNetworkStatsField, name, kind))
2790 for (name, (title, kind, _, doc)) in _NETWORK_STATS_FIELDS.items()])
2792 return _PrepareFieldList(fields, [])
2794 #: Fields for cluster information
2795 CLUSTER_FIELDS = _BuildClusterFields()
2797 #: Fields available for node queries
2798 NODE_FIELDS = _BuildNodeFields()
2800 #: Fields available for instance queries
2801 INSTANCE_FIELDS = _BuildInstanceFields()
2803 #: Fields available for lock queries
2804 LOCK_FIELDS = _BuildLockFields()
2806 #: Fields available for node group queries
2807 GROUP_FIELDS = _BuildGroupFields()
2809 #: Fields available for operating system queries
2810 OS_FIELDS = _BuildOsFields()
2812 #: Fields available for extstorage provider queries
2813 EXTSTORAGE_FIELDS = _BuildExtStorageFields()
2815 #: Fields available for job queries
2816 JOB_FIELDS = _BuildJobFields()
2818 #: Fields available for exports
2819 EXPORT_FIELDS = _BuildExportFields()
2821 #: Fields available for network queries
2822 NETWORK_FIELDS = _BuildNetworkFields()
2824 #: All available resources
2826 constants.QR_CLUSTER: CLUSTER_FIELDS,
2827 constants.QR_INSTANCE: INSTANCE_FIELDS,
2828 constants.QR_NODE: NODE_FIELDS,
2829 constants.QR_LOCK: LOCK_FIELDS,
2830 constants.QR_GROUP: GROUP_FIELDS,
2831 constants.QR_OS: OS_FIELDS,
2832 constants.QR_EXTSTORAGE: EXTSTORAGE_FIELDS,
2833 constants.QR_JOB: JOB_FIELDS,
2834 constants.QR_EXPORT: EXPORT_FIELDS,
2835 constants.QR_NETWORK: NETWORK_FIELDS,
2838 #: All available field lists
2839 ALL_FIELD_LISTS = ALL_FIELDS.values()