Add job failure output detection regexes

This allows users to trigger the new early failure detection by
matching regexes in the streaming job output.

For example, if a unit test job outputs something sufficiently
unique on failure, one could write a regex that matches that and
triggers the early failure detection before the playbook completes.

For hour-long unit test jobs, this could save a considerable amount
of time.

Note that this adds the google-re2 library to the Ansible venvs.  It
has manylinux wheels available, so is easy to install with
zuul-manage-ansible.  In Zuul itself, we use the fb-re2 library which
requires compilation and is therefore more difficult to use with
zuul-manage-ansible.  Presumably using fb-re2 to validate the syntax
and then later actually using google-re2 to run the regexes is
sufficient.  We may want to switch Zuul to use google-re2 later for
consistency.

Change-Id: Ifc9454767385de4c96e6da6d6f41bcb936aa24cd
This commit is contained in:
James E. Blair committed 2023-08-21 16:41:21 -07:00
1 parent f04d80912e
commit 1b042ba4ab
12 files changed
+231 -3

No files matched your search

+23
View File
@@ -1139,6 +1139,29 @@ Here is an example of two job definitions:
:attr:`job.deduplicate` may be set to ``true`` to ignore the
heuristic and deduplicate anyway.
.. attr:: failure-output
A regular expression (or list of regular expressions) that
should be matched against job output to determine if the job is
going to fail. Matches are performed line-by-line (multiline
regular expressions will not be effective).
This option is not required; job failure is determined by the
result code from its Ansible playbooks. However, if this option
is supplied, and one of the regular expressions matches a line
in the streaming output from the job, Zuul will be able to
anticipate the failure before the completion of the playbook.
In this case, it will be able to restart jobs for changes behind
it in a dependent pipeline.
When inheriting or applying variants this option is combined
so that regular expressions from all parents and variants used
will be applied.
Use caution when specifying this option. If an early failure is
triggered, the job result will be recorded as FAILURE even if
the job playbooks ultimately succeed.
.. attr:: workspace-scheme
:default: golang
@@ -0,0 +1,8 @@
---
features:
- |
A new job configuration option, :attr:`job.failure-output`, has
been added to allow users to specify regular expressions which,
when seen in the streaming job output, will trigger the early
failure detection in Zuul so that dependent pipeline gate resets
may begin before the completion of a failed job.
@@ -0,0 +1,17 @@
- hosts: localhost
tasks:
- file:
path: "{{zuul._test.test_root}}/builds/{{zuul.build}}.output_failure_start.flag"
state: touch
- debug:
msg: "Waiting for {{zuul._test.test_root}}/builds/{{zuul.build}}/output_failure_continue1_flag"
- wait_for:
state: present
path: "{{zuul._test.test_root}}/builds/{{zuul.build}}/output_failure_continue1_flag"
- shell: "echo This output indicates failure"
- debug:
msg: "Waiting for {{zuul._test.test_root}}/builds/{{zuul.build}}/output_failure_continue2_flag"
- wait_for:
state: present
path: "{{zuul._test.test_root}}/builds/{{zuul.build}}/output_failure_continue2_flag"
# Do not fail; this test also verifies that an early failure is sticky.
@@ -56,6 +56,17 @@
# This won't actually be run
- playbooks/wait.yaml
- job:
name: output-failure
files:
- output-failure.txt
failure-output:
- "^.*output indicates failure.*$"
run:
- playbooks/output-failure.yaml
post-run:
- playbooks/wait.yaml
- job:
name: wait
run:
@@ -74,10 +85,12 @@
jobs:
- early-failure
- pre-failure
- output-failure
gate:
jobs:
- early-failure
- pre-failure
- output-failure
- project:
name: org/project2
+98
View File
@@ -6065,6 +6065,104 @@ class TestEarlyFailure(AnsibleZuulTestCase):
dict(name='wait', result='SUCCESS', changes='2,1'),
], ordered=True)
def test_early_failure_output(self):
file_dict = {'output-failure.txt': ''}
A = self.fake_gerrit.addFakeChange('org/project1', 'master', 'A',
files=file_dict)
A.addApproval('Code-Review', 2)
self.fake_gerrit.addEvent(A.addApproval('Approved', 1))
self.log.debug("Wait for the first change to start its job")
for _ in iterate_timeout(30, 'job A started'):
if len(self.builds) == 1:
break
A_build = self.builds[0]
start = os.path.join(self.jobdir_root, A_build.uuid +
'.output_failure_start.flag')
for _ in iterate_timeout(30, 'job A running'):
if os.path.exists(start):
break
self.log.debug("Add a second change which will test with the first")
B = self.fake_gerrit.addFakeChange('org/project2', 'master', 'B')
B.addApproval('Code-Review', 2)
self.fake_gerrit.addEvent(B.addApproval('Approved', 1))
self.log.debug("Wait for the second change to start its job")
for _ in iterate_timeout(30, 'job B started'):
if len(self.builds) == 2:
break
B_build = self.builds[1]
start = os.path.join(self.jobdir_root, B_build.uuid +
'.wait_start.flag')
for _ in iterate_timeout(30, 'job B running'):
if os.path.exists(start):
break
self.log.debug("Continue the first job which will output failure text")
flag_path = os.path.join(self.jobdir_root, A_build.uuid,
'output_failure_continue1_flag')
self.log.debug("Writing %s", flag_path)
with open(flag_path, "w") as of:
of.write("continue")
self.log.debug("Wait for the second job to be aborted "
"and restarted without the first change")
for _ in iterate_timeout(30, 'job B restarted'):
if len(self.builds) == 2:
B_build2 = self.builds[1]
if B_build2 != B_build:
break
self.log.debug("Continue the first job on to actual failure")
flag_path = os.path.join(self.jobdir_root, A_build.uuid,
'output_failure_continue2_flag')
self.log.debug("Writing %s", flag_path)
with open(flag_path, "w") as of:
of.write("continue")
self.log.debug("Wait for the first job to be in its post-run playbook")
start = os.path.join(self.jobdir_root, A_build.uuid +
'.wait_start.flag')
for _ in iterate_timeout(30, 'job A post running'):
if os.path.exists(start):
break
path = os.path.join(self.jobdir_root, A_build.uuid,
'work/logs/job-output.txt')
with open(path) as f:
output = f.read()
self.log.info(output)
self.assertTrue('Early failure in job, matched regex '
'"^.*output indicates failure.*$"' in output)
self.log.debug("Allow the first job to finish")
flag_path = os.path.join(self.jobdir_root, A_build.uuid,
'wait_continue_flag')
self.log.debug("Writing %s", flag_path)
with open(flag_path, "w") as of:
of.write("continue")
self.log.debug("Wait for the first job to finish")
for _ in iterate_timeout(30, 'job A complete'):
if A_build not in self.builds:
break
self.log.debug("Allow the restarted second job to finish")
flag_path = os.path.join(self.jobdir_root, B_build2.uuid,
'wait_continue_flag')
self.log.debug("Writing %s", flag_path)
with open(flag_path, "w") as of:
of.write("continue")
self.waitUntilSettled()
self.assertHistory([
dict(name='wait', result='ABORTED', changes='1,1 2,1'),
dict(name='output-failure', result='FAILURE', changes='1,1'),
dict(name='wait', result='SUCCESS', changes='2,1'),
], ordered=True)
class TestMaxNodesPerJob(AnsibleZuulTestCase):
tenant_config_file = 'config/multi-tenant/main.yaml'
+11
View File
@@ -359,6 +359,7 @@ class TestWeb(BaseTestWeb):
'extra_variables': {},
'files': [],
'final': False,
'failure_output': [],
'group_variables': {},
'host_variables': {},
'intermediate': False,
@@ -462,6 +463,7 @@ class TestWeb(BaseTestWeb):
'irrelevant_files': [],
'match_on_config_updates': True,
'final': False,
'failure_output': [],
'nodeset': {
'alternatives': [],
'groups': [],
@@ -515,6 +517,7 @@ class TestWeb(BaseTestWeb):
'irrelevant_files': [],
'match_on_config_updates': True,
'final': False,
'failure_output': [],
'nodeset': {
'alternatives': [],
'groups': [],
@@ -569,6 +572,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -695,6 +699,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -736,6 +741,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -777,6 +783,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -818,6 +825,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -887,6 +895,7 @@ class TestWeb(BaseTestWeb):
'description': None,
'files': [],
'final': False,
'failure_output': [],
'intermediate': False,
'irrelevant_files': [],
'match_on_config_updates': True,
@@ -1167,6 +1176,7 @@ class TestWeb(BaseTestWeb):
'projects': [],
'branch': 'master',
'cleanup_playbooks': [],
'failure_output': [],
'nodeset': {
'alternatives': [],
'groups': [],
@@ -1268,6 +1278,7 @@ class TestWeb(BaseTestWeb):
'host_vars': {},
'items': [],
'job': 'noop',
'failure_output': [],
'nodeset': {'alternatives': [],
'groups': [], 'name': '', 'nodes': []},
'override_branch': None,
+29
View File
@@ -38,6 +38,7 @@ import logging
import logging.config
import json
import os
import re2
import socket
import threading
import time
@@ -122,7 +123,9 @@ class CallbackModule(default.CallbackModule):
self._play = None
self._streamers = []
self._streamers_stop = False
self.sent_failure_result = False
self.configure_logger()
self.configure_regexes()
self._items_done = False
self._deferred_result = None
self._playbook_name = None
@@ -144,6 +147,16 @@ class CallbackModule(default.CallbackModule):
self._result_logger = logging.getLogger(
'zuul.executor.ansible.result')
def configure_regexes(self):
try:
serialized = os.environ.get('ZUUL_JOB_FAILURE_OUTPUT', '[]')
regexes = json.loads(serialized)
self.failure_output = [re2.compile(x) for x in regexes]
except Exception as e:
self._log("Error compiling failure output regexes: %s"
% (str(e),), job=False, executor=True)
self.failure_output = []
def _log(self, msg, ts=None, job=True, executor=False, debug=False):
# With the default "linear" strategy (and likely others),
# Ansible will send the on_task_start callback, and then fork
@@ -280,11 +293,24 @@ class CallbackModule(default.CallbackModule):
ts, ln = line.split(' | ', 1)
self._log("%s | %s " % (host, ln), ts=ts)
self._check_failure_output(host, ln)
return False
else:
self._log("%s | %s " % (host, line))
self._check_failure_output(host, line)
return False
def _check_failure_output(self, host, line):
if self.sent_failure_result:
return
for fail_re in self.failure_output:
if fail_re.match(line):
self._log(
'%s | Early failure in job, matched regex "%s"' % (
host, fail_re.pattern,))
self._result_logger.info("failure")
self.sent_failure_result = True
def _log_module_failure(self, result, result_dict):
if 'module_stdout' in result_dict and result_dict['module_stdout']:
self._log_message(
@@ -443,6 +469,7 @@ class CallbackModule(default.CallbackModule):
for line in stdout_lines:
hostname = self._get_hostname(result)
self._log("%s | %s " % (hostname, line))
self._check_failure_output(hostname, line)
def _v2_runner_on_failed(self, result, ignore_errors=False):
result_dict = dict(result._result)
@@ -473,8 +500,10 @@ class CallbackModule(default.CallbackModule):
def v2_runner_on_failed(self, result, ignore_errors=False):
ret = self._v2_runner_on_failed(result, ignore_errors)
if (not ignore_errors and
not self.sent_failure_result and
not is_rescuable(result._task)):
self._result_logger.info("failure")
self.sent_failure_result = True
return ret
def v2_runner_on_unreachable(self, result):
+11
View File
@@ -21,6 +21,7 @@ import logging
import textwrap
import io
import re
import re2
import subprocess
import voluptuous as vs
@@ -838,6 +839,7 @@ class JobParser(object):
'match-on-config-updates': bool,
'workspace-scheme': vs.Any('golang', 'flat', 'unique'),
'deduplicate': vs.Any(bool, 'auto'),
'failure-output': to_list(str),
}
job_name = {vs.Required('name'): str}
@@ -1173,6 +1175,15 @@ class JobParser(object):
job.setFileMatcher(as_list(conf['files']))
if 'irrelevant-files' in conf:
job.setIrrelevantFileMatcher(as_list(conf['irrelevant-files']))
if 'failure-output' in conf:
failure_output = as_list(conf['failure-output'])
# Test compilation to detect errors, but the zuul_stream
# callback plugin is what actually needs re objects, so we
# let it recompile them later.
for x in failure_output:
re2.compile(x)
job.failure_output = tuple(failure_output)
job.freeze()
return job
+7
View File
@@ -978,6 +978,10 @@ class AnsibleJob(object):
with executor_server.zk_context as ctx:
self.job = FrozenJob.fromZK(ctx, arguments["job_ref"])
self.arguments["zuul"].update(zuul_params_from_job(self.job))
if self.job.failure_output:
self.failure_output = json.dumps(self.job.failure_output)
else:
self.failure_output = '[]'
self.early_failure = False
self.zuul_event_id = self.arguments["zuul_event_id"]
@@ -2753,6 +2757,7 @@ class AnsibleJob(object):
if not key.startswith("ZUUL_")}
env_copy.update(self.ssh_agent.env)
env_copy['ZUUL_JOB_LOG_CONFIG'] = self.jobdir.logging_json
env_copy['ZUUL_JOB_FAILURE_OUTPUT'] = self.failure_output
env_copy['ZUUL_JOBDIR'] = self.jobdir.root
if self.executor_server.log_console_port != DEFAULT_STREAM_PORT:
env_copy['ZUUL_CONSOLE_PORT'] = str(
@@ -2883,6 +2888,8 @@ class AnsibleJob(object):
self.early_failure = True
self.executor_server.updateBuildStatus(
self.build_request, {'pre_fail': True})
# No need to pre-fail again
allow_pre_fail = False
else:
idx += 1
if idx < BUFFER_LINES_FOR_SYNTAX:
+1 -1
View File
@@ -2,7 +2,7 @@
[common]
default_version = 6
# OpenStackSDK 0.99.0 coincides with CORS header problems in some providers
requirements = openstacksdk<0.99 openshift jmespath google-cloud-storage pywinrm boto3 azure-storage-blob ibm-cos-sdk netaddr passlib
requirements = openstacksdk<0.99 openshift jmespath google-cloud-storage pywinrm boto3 azure-storage-blob ibm-cos-sdk netaddr passlib google-re2
[6]
requirements = ansible>=6.0,<7.0
+12 -2
View File
@@ -2321,6 +2321,7 @@ class FrozenJob(zkobject.ZKObject):
'workspace_scheme',
'config_hash',
'deduplicate',
'failure_output',
)
job_data_attributes = ('artifact_data',
@@ -2444,7 +2445,7 @@ class FrozenJob(zkobject.ZKObject):
def deserialize(self, raw, context):
# Ensure that any special handling in this method is matched
# in Job.freezeJob so that FrozenJobs are identical regardless
# of whether they have been desiraliazed.
# of whether they have been deserialized.
data = super().deserialize(raw, context)
# MODEL_API < 8
@@ -2461,6 +2462,10 @@ class FrozenJob(zkobject.ZKObject):
if 'ansible_split_streams' not in data:
data['ansible_split_streams'] = None
# MODEL_API < 15
if 'failure_output' not in data:
data['failure_output'] = []
if hasattr(self, 'nodeset_alternatives'):
alts = self.nodeset_alternatives
else:
@@ -2746,6 +2751,7 @@ class Job(ConfigObject):
d['post_review'] = self.post_review
d['match_on_config_updates'] = self.match_on_config_updates
d['deduplicate'] = self.deduplicate
d['failure_output'] = self.failure_output
if self.isBase():
d['parent'] = None
elif self.parent:
@@ -2825,6 +2831,7 @@ class Job(ConfigObject):
override_checkout=None,
post_review=None,
workspace_scheme=SCHEME_GOLANG,
failure_output=(),
)
# These are generally internal attributes which are not
@@ -3000,6 +3007,7 @@ class Job(ConfigObject):
]
kw['dependencies'] = frozenset(kw['dependencies'])
kw['semaphores'] = list(kw['semaphores'])
kw['failure_output'] = list(kw['failure_output'])
# Don't add buildset to attributes since it's not serialized
kw['buildset'] = buildset
return FrozenJob.new(context, **kw)
@@ -3290,7 +3298,7 @@ class Job(ConfigObject):
'roles', 'variables', 'extra_variables',
'host_variables', 'group_variables',
'required_projects', 'allowed_projects',
'semaphores']):
'semaphores', 'failure_output']):
setattr(self, k, other._get(k))
# Don't set final above so that we don't trip an error halfway
@@ -3402,6 +3410,8 @@ class Job(ConfigObject):
self.semaphores = tuple(
sorted(other.semaphores + self.semaphores,
key=lambda x: x.name))
if other._get('failure_output') is not None:
self.failure_output = self.failure_output + other.failure_output
pb_semaphores = set()
for pb in self.run + self.pre_run + self.post_run + self.cleanup_run:
+1
View File
@@ -1702,6 +1702,7 @@ class ZuulWebAPI(object):
params['host_vars'] = job.host_variables
params['group_vars'] = job.group_variables
params['secret_vars'] = job.secret_parent_data
params['failure_output'] = job.failure_output
ret = params
return ret