+def _JobUnavailInner(fn, ctx, (job_id, job)): # pylint: disable=W0613
+ """Return L{_FS_UNAVAIL} if job is None.
+
+ When listing specifc jobs (e.g. "gnt-job list 1 2 3"), a job may not be
+ found, in which case this function converts it to L{_FS_UNAVAIL}.
+
+ """
+ if job is None:
+ return _FS_UNAVAIL
+ else:
+ return fn(job)
+
+
+def _JobUnavail(inner):
+ """Wrapper for L{_JobUnavailInner}.
+
+ """
+ return compat.partial(_JobUnavailInner, inner)
+
+
+def _PerJobOpInner(fn, job):
+ """Executes a function per opcode in a job.
+
+ """
+ return map(fn, job.ops)
+
+
+def _PerJobOp(fn):
+ """Wrapper for L{_PerJobOpInner}.
+
+ """
+ return _JobUnavail(compat.partial(_PerJobOpInner, fn))
+
+
+def _JobTimestampInner(fn, job):
+ """Converts unavailable timestamp to L{_FS_UNAVAIL}.
+
+ """
+ timestamp = fn(job)
+
+ if timestamp is None:
+ return _FS_UNAVAIL
+ else:
+ return timestamp
+
+
+def _JobTimestamp(fn):
+ """Wrapper for L{_JobTimestampInner}.
+
+ """
+ return _JobUnavail(compat.partial(_JobTimestampInner, fn))
+
+
+def _BuildJobFields():
+ """Builds list of fields for job queries.
+
+ """
+ fields = [
+ (_MakeField("id", "ID", QFT_NUMBER, "Job ID"),
+ None, QFF_JOB_ID, lambda _, (job_id, job): job_id),
+ (_MakeField("status", "Status", QFT_TEXT, "Job status"),
+ None, 0, _JobUnavail(lambda job: job.CalcStatus())),
+ (_MakeField("priority", "Priority", QFT_NUMBER,
+ ("Current job priority (%s to %s)" %
+ (constants.OP_PRIO_LOWEST, constants.OP_PRIO_HIGHEST))),
+ None, 0, _JobUnavail(lambda job: job.CalcPriority())),
+ (_MakeField("archived", "Archived", QFT_BOOL, "Whether job is archived"),
+ JQ_ARCHIVED, 0, lambda _, (job_id, job): job.archived),
+ (_MakeField("ops", "OpCodes", QFT_OTHER, "List of all opcodes"),
+ None, 0, _PerJobOp(lambda op: op.input.__getstate__())),
+ (_MakeField("opresult", "OpCode_result", QFT_OTHER,
+ "List of opcodes results"),
+ None, 0, _PerJobOp(operator.attrgetter("result"))),
+ (_MakeField("opstatus", "OpCode_status", QFT_OTHER,
+ "List of opcodes status"),
+ None, 0, _PerJobOp(operator.attrgetter("status"))),
+ (_MakeField("oplog", "OpCode_log", QFT_OTHER,
+ "List of opcode output logs"),
+ None, 0, _PerJobOp(operator.attrgetter("log"))),
+ (_MakeField("opstart", "OpCode_start", QFT_OTHER,
+ "List of opcode start timestamps (before acquiring locks)"),
+ None, 0, _PerJobOp(operator.attrgetter("start_timestamp"))),
+ (_MakeField("opexec", "OpCode_exec", QFT_OTHER,
+ "List of opcode execution start timestamps (after acquiring"
+ " locks)"),
+ None, 0, _PerJobOp(operator.attrgetter("exec_timestamp"))),
+ (_MakeField("opend", "OpCode_end", QFT_OTHER,
+ "List of opcode execution end timestamps"),
+ None, 0, _PerJobOp(operator.attrgetter("end_timestamp"))),
+ (_MakeField("oppriority", "OpCode_prio", QFT_OTHER,
+ "List of opcode priorities"),
+ None, 0, _PerJobOp(operator.attrgetter("priority"))),
+ (_MakeField("summary", "Summary", QFT_OTHER,
+ "List of per-opcode summaries"),
+ None, 0, _PerJobOp(lambda op: op.input.Summary())),
+ ]
+
+ # Timestamp fields
+ for (name, attr, title, desc) in [
+ ("received_ts", "received_timestamp", "Received",
+ "Timestamp of when job was received"),
+ ("start_ts", "start_timestamp", "Start", "Timestamp of job start"),
+ ("end_ts", "end_timestamp", "End", "Timestamp of job end"),
+ ]:
+ getter = operator.attrgetter(attr)
+ fields.extend([
+ (_MakeField(name, title, QFT_OTHER,
+ "%s (tuple containing seconds and microseconds)" % desc),
+ None, QFF_SPLIT_TIMESTAMP, _JobTimestamp(getter)),
+ ])
+
+ return _PrepareFieldList(fields, [])
+
+
+def _GetExportName(_, (node_name, expname)): # pylint: disable=W0613
+ """Returns an export name if available.
+
+ """
+ if expname is None:
+ return _FS_UNAVAIL
+ else:
+ return expname
+
+
+def _BuildExportFields():
+ """Builds list of fields for exports.
+
+ """
+ fields = [
+ (_MakeField("node", "Node", QFT_TEXT, "Node name"),
+ None, QFF_HOSTNAME, lambda _, (node_name, expname): node_name),
+ (_MakeField("export", "Export", QFT_TEXT, "Export name"),
+ None, 0, _GetExportName),
+ ]
+
+ return _PrepareFieldList(fields, [])
+
+
+_CLUSTER_VERSION_FIELDS = {
+ "software_version": ("SoftwareVersion", QFT_TEXT, constants.RELEASE_VERSION,
+ "Software version"),
+ "protocol_version": ("ProtocolVersion", QFT_NUMBER,
+ constants.PROTOCOL_VERSION,
+ "RPC protocol version"),
+ "config_version": ("ConfigVersion", QFT_NUMBER, constants.CONFIG_VERSION,
+ "Configuration format version"),
+ "os_api_version": ("OsApiVersion", QFT_NUMBER, max(constants.OS_API_VERSIONS),
+ "API version for OS template scripts"),
+ "export_version": ("ExportVersion", QFT_NUMBER, constants.EXPORT_VERSION,
+ "Import/export file format version"),
+ }
+
+
+_CLUSTER_SIMPLE_FIELDS = {
+ "cluster_name": ("Name", QFT_TEXT, QFF_HOSTNAME, "Cluster name"),
+ "master_node": ("Master", QFT_TEXT, QFF_HOSTNAME, "Master node name"),
+ "volume_group_name": ("VgName", QFT_TEXT, 0, "LVM volume group name"),
+ }
+
+
+class ClusterQueryData:
+ def __init__(self, cluster, drain_flag, watcher_pause):
+ """Initializes this class.
+
+ @type cluster: L{objects.Cluster}
+ @param cluster: Instance of cluster object
+ @type drain_flag: bool
+ @param drain_flag: Whether job queue is drained
+ @type watcher_pause: number
+ @param watcher_pause: Until when watcher is paused (Unix timestamp)
+
+ """
+ self._cluster = cluster
+ self.drain_flag = drain_flag
+ self.watcher_pause = watcher_pause
+
+ def __iter__(self):
+ return iter([self._cluster])
+
+
+def _ClusterWatcherPause(ctx, _):
+ """Returns until when watcher is paused (if available).
+
+ """
+ if ctx.watcher_pause is None:
+ return _FS_UNAVAIL
+ else:
+ return ctx.watcher_pause
+
+
+def _BuildClusterFields():
+ """Builds list of fields for cluster information.
+
+ """
+ fields = [
+ (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), CQ_CONFIG, 0,
+ lambda ctx, cluster: list(cluster.GetTags())),
+ (_MakeField("architecture", "ArchInfo", QFT_OTHER,
+ "Architecture information"), None, 0,
+ lambda ctx, _: runtime.GetArchInfo()),
+ (_MakeField("drain_flag", "QueueDrained", QFT_BOOL,
+ "Flag whether job queue is drained"), CQ_QUEUE_DRAINED, 0,
+ lambda ctx, _: ctx.drain_flag),
+ (_MakeField("watcher_pause", "WatcherPause", QFT_TIMESTAMP,
+ "Until when watcher is paused"), CQ_WATCHER_PAUSE, 0,
+ _ClusterWatcherPause),
+ ]
+
+ # Simple fields
+ fields.extend([
+ (_MakeField(name, title, kind, doc), CQ_CONFIG, flags, _GetItemAttr(name))
+ for (name, (title, kind, flags, doc)) in _CLUSTER_SIMPLE_FIELDS.items()
+ ],)
+
+ # Version fields
+ fields.extend([
+ (_MakeField(name, title, kind, doc), None, 0, _StaticValue(value))
+ for (name, (title, kind, value, doc)) in _CLUSTER_VERSION_FIELDS.items()])
+
+ # Add timestamps
+ fields.extend(_GetItemTimestampFields(CQ_CONFIG))
+
+ return _PrepareFieldList(fields, [
+ ("name", "cluster_name")])
+
+
+class NetworkQueryData:
+ """Data container for network data queries.
+
+ """
+ def __init__(self, networks, network_to_groups,
+ network_to_instances, stats):
+ """Initializes this class.
+
+ @param networks: List of network objects
+ @type network_to_groups: dict; network UUID as key
+ @param network_to_groups: Per-network list of groups
+ @type network_to_instances: dict; network UUID as key
+ @param network_to_instances: Per-network list of instances
+ @type stats: dict; network UUID as key
+ @param stats: Per-network usage statistics
+
+ """
+ self.networks = networks
+ self.network_to_groups = network_to_groups
+ self.network_to_instances = network_to_instances
+ self.stats = stats
+
+ def __iter__(self):
+ """Iterate over all networks.
+
+ """
+ for net in self.networks:
+ if self.stats:
+ self.curstats = self.stats.get(net.uuid, None)
+ else:
+ self.curstats = None
+ yield net
+
+
+_NETWORK_SIMPLE_FIELDS = {
+ "name": ("Network", QFT_TEXT, 0, "The network"),
+ "network": ("Subnet", QFT_TEXT, 0, "The subnet"),
+ "gateway": ("Gateway", QFT_OTHER, 0, "The gateway"),
+ "network6": ("IPv6Subnet", QFT_OTHER, 0, "The ipv6 subnet"),
+ "gateway6": ("IPv6Gateway", QFT_OTHER, 0, "The ipv6 gateway"),
+ "mac_prefix": ("MacPrefix", QFT_OTHER, 0, "The mac prefix"),
+ "network_type": ("NetworkType", QFT_OTHER, 0, "The network type"),
+ }
+
+
+_NETWORK_STATS_FIELDS = {
+ "free_count": ("FreeCount", QFT_NUMBER, 0, "How many addresses are free"),
+ "reserved_count": ("ReservedCount", QFT_NUMBER, 0,
+ "How many addresses are reserved"),
+ "map": ("Map", QFT_TEXT, 0, "The actual mapping"),
+ "external_reservations": ("ExternalReservations", QFT_TEXT, 0,
+ "The external reservations"),
+ }
+
+
+def _GetNetworkStatsField(field, kind, ctx):
+ """Gets the value of a "stats" field from L{NetworkQueryData}.
+
+ @param field: Field name
+ @param kind: Data kind, one of L{constants.QFT_ALL}
+ @type ctx: L{NetworkQueryData}
+
+ """
+
+ try:
+ value = ctx.curstats[field]
+ except KeyError:
+ return _FS_UNAVAIL
+
+ if kind == QFT_TEXT:
+ return value
+
+ assert kind in (QFT_NUMBER, QFT_UNIT)
+
+ # Try to convert into number
+ try:
+ return int(value)
+ except (ValueError, TypeError):
+ logging.exception("Failed to convert network field '%s' (value %r) to int",
+ field, value)
+ return _FS_UNAVAIL
+
+
+def _BuildNetworkFields():
+ """Builds list of fields for network queries.
+
+ """
+ fields = [
+ (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, 0,
+ lambda ctx, inst: list(inst.GetTags())),
+ ]
+
+ # Add simple fields
+ fields.extend([
+ (_MakeField(name, title, kind, doc),
+ NETQ_CONFIG, 0, _GetItemAttr(name))
+ for (name, (title, kind, _, doc)) in _NETWORK_SIMPLE_FIELDS.items()])
+
+ def _GetLength(getter):
+ return lambda ctx, network: len(getter(ctx)[network.uuid])
+
+ def _GetSortedList(getter):
+ return lambda ctx, network: utils.NiceSort(getter(ctx)[network.uuid])
+
+ network_to_groups = operator.attrgetter("network_to_groups")
+ network_to_instances = operator.attrgetter("network_to_instances")
+
+ # Add fields for node groups
+ fields.extend([
+ (_MakeField("group_cnt", "NodeGroups", QFT_NUMBER, "Number of nodegroups"),
+ NETQ_GROUP, 0, _GetLength(network_to_groups)),
+ (_MakeField("group_list", "GroupList", QFT_OTHER, "List of nodegroups"),
+ NETQ_GROUP, 0, _GetSortedList(network_to_groups)),
+ ])
+
+ # Add fields for instances
+ fields.extend([
+ (_MakeField("inst_cnt", "Instances", QFT_NUMBER, "Number of instances"),
+ NETQ_INST, 0, _GetLength(network_to_instances)),
+ (_MakeField("inst_list", "InstanceList", QFT_OTHER, "List of instances"),
+ NETQ_INST, 0, _GetSortedList(network_to_instances)),
+ ])
+
+ # Add fields for usage statistics
+ fields.extend([
+ (_MakeField(name, title, kind, doc), NETQ_STATS, 0,
+ compat.partial(_GetNetworkStatsField, name, kind))
+ for (name, (title, kind, _, doc)) in _NETWORK_STATS_FIELDS.items()])
+
+ return _PrepareFieldList(fields, [])
+
+#: Fields for cluster information
+CLUSTER_FIELDS = _BuildClusterFields()
+