From 86b10708b99bfeee2e781aebd1c855f2bbca53de Mon Sep 17 00:00:00 2001 From: Andreas Maier Date: Tue, 28 Nov 2023 03:58:59 +0100 Subject: [PATCH] Added handling of evaluation errors for 'if' conditions Details: * The 'if' conditions in the default metric definition file should not cause issues, but because the file can be modified by users, the current approach of ending with a Python traceback has been improved to now handle possible exceptions when evaluating the expression. Signed-off-by: Andreas Maier --- docs/changes.rst | 3 +++ .../zhmc_prometheus_exporter.py | 15 +++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/changes.rst b/docs/changes.rst index 84357c6b..4d906578 100644 --- a/docs/changes.rst +++ b/docs/changes.rst @@ -110,6 +110,9 @@ Released: not yet * Added adapter name and port index as two new labels 'adapter' and 'port' to metric group 'partition-attached-network-interface'. (issue #347) +* Added handling of evaluation errors for 'if' conditions in metric definition + files. + **Cleanup:** **Known issues:** diff --git a/zhmc_prometheus_exporter/zhmc_prometheus_exporter.py b/zhmc_prometheus_exporter/zhmc_prometheus_exporter.py index a51fb6c2..5172fa61 100755 --- a/zhmc_prometheus_exporter/zhmc_prometheus_exporter.py +++ b/zhmc_prometheus_exporter/zhmc_prometheus_exporter.py @@ -516,11 +516,13 @@ def eval_condition(condition, hmc_version, se_version): hmc_version (string): Expression variable: HMC version as a string. se_version (string): Expression variable: SE/CPC version as a string. + May be None. Returns: bool: Evaluated condition """ + org_condition = condition hmc_version = split_version(hmc_version, 3) if se_version: se_version = split_version(se_version, 3) @@ -530,10 +532,15 @@ def eval_condition(condition, hmc_version, se_version): break condition = "{}{}{}".format( m.group(1), split_version(m.group(2), 3), m.group(3)) - # pylint: disable=eval-used - condition = eval(condition, None, - dict(hmc_version=hmc_version, se_version=se_version)) - return condition + try: + # pylint: disable=eval-used + return eval(condition, None, + dict(hmc_version=hmc_version, se_version=se_version)) + except Exception as exc: # pylint: disable=broad-exception-caught + warnings.warn("Ignoring item because its condition {!r} does not " + "properly evaluate: {}: {}". + format(org_condition, exc.__class__.__name__, exc)) + return False # Metrics context creation & deletion and retrieval derived from