code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Determine the number of failures we're going to process
# A failure is a revision + all of the jobs that were fixed by it
number_of_failures = int((target / 100) * len(failures))
low_value_jobs = []
for jobtype in active_jobs:
# Determine if removing an active job will reduce the num... | def build_removals(active_jobs, failures, target) | active_jobs - all possible desktop & android jobs on Treeherder (no PGO)
failures - list of all failures
target - percentage of failures we're going to process
Return list of jobs to remove and list of revisions that are regressed | 5.581114 | 5.146904 | 1.084363 |
total = len(fixed_by_commit_jobs)
logger.info("Processing %s revision(s)", total)
active_jobs = job_priorities_to_jobtypes()
low_value_jobs = build_removals(
active_jobs=active_jobs,
failures=fixed_by_commit_jobs,
target=target)
# Only return high value jobs
for lo... | def get_high_value_jobs(fixed_by_commit_jobs, target=100) | fixed_by_commit_jobs:
Revisions and jobs that have been starred that are fixed with a push or a bug
target:
Percentage of failures to analyze | 3.894063 | 3.964729 | 0.982176 |
self.state = self.STATES['step_in_progress']
self.stepnum += 1
self.steps.append({
"name": name,
"started": timestamp,
"started_linenumber": lineno,
"errors": [],
}) | def start_step(self, lineno, name="Unnamed step", timestamp=None) | Create a new step and update the state to reflect we're now in the middle of a step. | 4.690453 | 4.031925 | 1.163328 |
self.state = self.STATES['step_finished']
step_errors = self.sub_parser.get_artifact()
step_error_count = len(step_errors)
if step_error_count > settings.PARSER_MAX_STEP_ERROR_LINES:
step_errors = step_errors[:settings.PARSER_MAX_STEP_ERROR_LINES]
self.ar... | def end_step(self, lineno, timestamp=None, result_code=None) | Fill in the current step's summary and update the state to show the current step has ended. | 7.457176 | 7.410628 | 1.006281 |
if self.state == self.STATES['step_in_progress']:
# We've reached the end of the log without seeing the final "step finish"
# marker, which would normally have triggered updating the step. As such we
# must manually close out the current step, so things like result, ... | def finish_parse(self, last_lineno_seen) | Clean-up/summary tasks run at the end of parsing. | 20.725492 | 19.085985 | 1.085901 |
match = self.RE_TINDERBOXPRINT.match(line) if line else None
if match:
line = match.group('line')
for regexp_item in self.TINDERBOX_REGEXP_TUPLE:
match = regexp_item['re'].match(line)
if match:
artifact = match.groupdi... | def parse_line(self, line, lineno) | Parse a single line of the log | 4.670633 | 4.696713 | 0.994447 |
# TaskCluster logs are a bit wonky.
#
# TaskCluster logs begin with output coming from TaskCluster itself,
# before it has transitioned control of the task to the configured
# process. These "internal" logs look like the following:
#
# [taskcluster 2016... | def parse_line(self, line, lineno) | Check a single line for an error. Keeps track of the linenumber | 9.338872 | 9.437988 | 0.989498 |
log = JobLog.objects.get(id=pk)
return Response(self._log_as_dict(log)) | def retrieve(self, request, project, pk=None) | Returns a job_log_url object given its ID | 7.013665 | 5.004616 | 1.401439 |
job_ids = request.query_params.getlist('job_id')
if not job_ids:
raise ParseError(
detail="The job_id parameter is mandatory for this endpoint")
try:
job_ids = [int(job_id) for job_id in job_ids]
except ValueError:
raise ParseE... | def list(self, request, project) | GET method implementation for list view
job_id -- Mandatory filter indicating which job these log belongs to. | 2.756822 | 2.514707 | 1.096279 |
if weight_fn is None:
weight_fn = default_weights
# get a weighted average for the full set of data -- this is complicated
# by the fact that we might have multiple data points from each revision
# which we would want to weight equally -- do this by creating a set of
# weights only for... | def analyze(revision_data, weight_fn=None) | Returns the average and sample variance (s**2) of a list of floats.
`weight_fn` is a function that takes a list index and a window width, and
returns a weight that is used to calculate a weighted average. For example,
see `default_weights` or `linear_weights` below. If no function is passed,
`default... | 3.336623 | 3.241956 | 1.029201 |
if i >= n:
return 0.0
return float(n - i) / float(n) | def linear_weights(i, n) | A window function that falls off arithmetically.
This is used to calculate a weighted moving average (WMA) that gives higher
weight to changes near the point being analyzed, and smooth out changes at
the opposite edge of the moving window. See bug 879903 for details. | 3.65075 | 5.049783 | 0.722952 |
if not w1 or not w2:
return 0
s1 = analyze(w1, weight_fn)
s2 = analyze(w2, weight_fn)
delta_s = s2['avg'] - s1['avg']
if delta_s == 0:
return 0
if s1['variance'] == 0 and s2['variance'] == 0:
return float('inf')
return delta_s / (((s1['variance'] / s1['n']) + ... | def calc_t(w1, w2, weight_fn=None) | Perform a Students t-test on the two sets of revision data.
See the analyze() function for a description of the `weight_fn` argument. | 2.411589 | 2.383897 | 1.011616 |
new_data = []
guids = [datum['job']['job_guid'] for datum in data]
state_map = {
guid: state for (guid, state) in Job.objects.filter(
guid__in=guids).values_list('guid', 'state')
}
for datum in data:
job = datum['job']
if not state_map.get(job['job_guid']):... | def _remove_existing_jobs(data) | Remove jobs from data where we already have them in the same state.
1. split the incoming jobs into pending, running and complete.
2. fetch the ``job_guids`` from the db that are in the same state as they
are in ``data``.
3. build a new list of jobs in ``new_data`` that are not already in
the... | 3.042575 | 2.807775 | 1.083625 |
# importing here to avoid an import loop
from treeherder.log_parser.tasks import parse_logs
task_types = {
"errorsummary_json",
"buildbot_text",
"builds-4h"
}
job_log_ids = []
for job_log in job_logs:
# a log can be submitted already parsed. So only sched... | def _schedule_log_parsing(job, job_logs, result) | Kick off the initial task that parses the log data.
log_data is a list of job log objects and the result for that job | 8.873776 | 8.870222 | 1.000401 |
exchange = Exchange(name, type="topic", passive=not create)
# bind the exchange to our connection so operations can be performed on it
bound_exchange = exchange(connection)
# ensure the exchange exists. Throw an error if it was created with
# passive=True and it doesn't exist.
bound_exch... | def get_exchange(connection, name, create=False) | Get a Kombu Exchange object using the passed in name.
Can create an Exchange but this is typically not wanted in production-like
environments and only useful for testing. | 5.680971 | 6.142656 | 0.92484 |
'''Return list of ref_data_name for job_priorities'''
jobs = []
# we cache the reference data names in order to reduce API calls
cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system)
ref_data_names_map = cache.get(cache_key)
if not ref_data_names_map:
... | def _process(self, project, build_system, job_priorities) | Return list of ref_data_name for job_priorities | 6.461244 | 5.807559 | 1.112558 |
'''
We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-mochitest-webgl-e10s-1"
'''
ignored_jobs = ... | def _build_ref_data_names(self, project, build_system) | We want all reference data names for every task that runs on a specific project.
For example:
* Buildbot - "Windows 8 64-bit mozilla-inbound debug test web-platform-tests-1"
* TaskCluster = "test-linux64/opt-mochitest-webgl-e10s-1" | 5.175502 | 2.461832 | 2.102297 |
try:
user = authenticate(request)
if not user:
raise AuthenticationFailed("User not authenticated.")
if not user.is_active:
raise AuthenticationFailed("This user has been disabled.")
login(request, user)
ret... | def login(self, request) | Verify credentials | 6.631744 | 6.644792 | 0.998036 |
fields = set()
for leaf in node:
if leaf.get('kind', None) == "Field":
fields.add(leaf["name"]["value"])
if leaf.get("selection_set", None):
fields = fields.union(collect_fields(leaf["selection_set"]["selections"]))
return fields | def collect_fields(node) | Get all the unique field names that are eligible for optimization
Requested a function like this be added to the ``info`` object
upstream in graphene_django:
https://github.com/graphql-python/graphene-django/issues/230 | 3.243596 | 3.035366 | 1.068601 |
fields = collect_fields(info_dict)
for field in fields:
if field in field_map:
field_name, opt = field_map[field]
qs = (qs.prefetch_related(field_name)
if opt == "prefetch" else qs.select_related(field_name))
return qs | def optimize(qs, info_dict, field_map) | Add either select_related or prefetch_related to fields of the qs | 3.230329 | 2.741871 | 1.178148 |
username = os.environ.get('ELASTICSEARCH_USERNAME')
password = os.environ.get('ELASTICSEARCH_PASSWORD')
if username and password:
return Elasticsearch(url, http_auth=(username, password))
return Elasticsearch(url) | def build_connection(url) | Build an Elasticsearch connection with the given url
Elastic.co's Heroku addon doesn't create credientials with access to the
cluster by default so they aren't exposed in the URL they provide either.
This function works around the situation by grabbing our credentials from
the environment via Django se... | 2.099077 | 1.95429 | 1.074087 |
# The parser may only need to run until it has seen a specific line.
# Once that's occurred, it can mark itself as complete, to save
# being run against later log lines.
if self.parser.complete:
return
# Perf data is stored in a json structure contained in a... | def parse_line(self, line) | Parse a single line of the log. | 11.012386 | 10.509747 | 1.047826 |
self.artifact[self.parser.name] = self.parser.get_artifact()
return self.artifact | def get_artifact(self) | Return the job artifact built by the parser. | 7.209158 | 4.053075 | 1.778689 |
failure_line = text_log_error.metadata.failure_line
logger.debug("Looking for test match in failure %d", failure_line.id)
if failure_line.action != "test_result" or failure_line.message is None:
return
f = {
'text_log_error___metadata__failure_line__action': 'test_result',
... | def precise_matcher(text_log_error) | Query for TextLogErrorMatches identical to matches of the given TextLogError. | 4.941144 | 4.756872 | 1.038738 |
# Note: Elasticsearch is currently disabled in all environments (see bug 1527868).
if not settings.ELASTICSEARCH_URL:
return []
failure_line = text_log_error.metadata.failure_line
if failure_line.action != "test_result" or not failure_line.message:
logger.debug("Skipped elasticsea... | def elasticsearch_matcher(text_log_error) | Query Elasticsearch and score the results.
Uses a filtered search checking test, status, expected, and the message
as a phrase query with non-alphabet tokens removed. | 3.634986 | 3.46913 | 1.047809 |
failure_line = text_log_error.metadata.failure_line
if (failure_line.action != "crash" or
failure_line.signature is None or
failure_line.signature == "None"):
return
f = {
'text_log_error___metadata__failure_line__action': 'crash',
'text_log_error___metadata__f... | def crash_signature_matcher(text_log_error) | Query for TextLogErrorMatches with the same crash signature.
Produces two queries, first checking if the same test produces matches
and secondly checking without the same test but lowering the produced
scores. | 4.578927 | 4.385738 | 1.044049 |
best_match = None
for match, message in matches:
self.matcher.set_seq1(message)
ratio = self.matcher.quick_ratio()
if best_match is None or ratio >= best_match[0]:
new_ratio = self.matcher.ratio()
if best_match is None or new_r... | def best_match(self, matches) | Find the most similar string to self.target.
Given a list of candidate strings find the closest match to
self.target, returning the best match with a score indicating closeness
of match.
:param matches: A list of candidate matches
:returns: A tuple of (score, best_match) | 3.018346 | 3.362082 | 0.897761 |
if not pushes:
logger.info("No new pushes to store")
return
for push in pushes:
store_push(repository, push) | def store_push_data(repository, pushes) | Stores push data in the treeherder database
pushes = [
{
"revision": "8afdb7debc82a8b6e0d56449dfdf916c77a7bf80",
"push_timestamp": 1378293517,
"author": "some-sheriff@mozilla.com",
"revisions": [
{
"comment": "Bug 911954 - Add forward declarat... | 3.357425 | 3.097896 | 1.083776 |
max_timestamp = datetime.datetime.now() - cycle_interval
# seperate datums into chunks
while True:
perf_datums_to_cycle = list(self.filter(
repository=repository,
push_timestamp__lt=max_timestamp).values_list('id', flat=True)[:chunk_size])
... | def cycle_data(self, repository, cycle_interval, chunk_size, sleep_time) | Delete data older than cycle_interval, splitting the target data
into chunks of chunk_size size. | 4.393202 | 4.365158 | 1.006425 |
try:
matches = failure_line.error.matches.all()
except AttributeError: # failure_line.error can return None
matches = []
tle_serializer = TextLogErrorMatchSerializer(matches, many=True)
classified_failures = models.ClassifiedFailure.objects.filter(error... | def to_representation(self, failure_line) | Manually add matches our wrapper of the TLEMetadata -> TLE relation.
I could not work out how to do this multiple relation jump with DRF (or
even if it was possible) so using this manual method instead. | 3.996667 | 3.84427 | 1.039642 |
bug_stats, bug_ids = self.get_bug_stats(startday, endday)
alt_date_bug_totals = self.get_alt_date_bug_totals(alt_startday, alt_endday, bug_ids)
test_run_count = self.get_test_runs(startday, endday)
# if fetch_bug_details fails, None is returned
bug_info = self.fetch_al... | def generate_bug_changes(self, startday, endday, alt_startday, alt_endday) | Returns a list of dicts containing a bug id, a bug comment (only
for bugs whose total number of daily or weekly occurrences meet
the appropriate threshold) and potentially an updated whiteboard
or priority status. | 3.842246 | 3.768207 | 1.019649 |
yesterday = date.today() - timedelta(days=1)
endday = datetime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59, 999)
if mode:
startday = yesterday - timedelta(days=numDays)
else:
# daily mode
startday = yesterday
return st... | def calculate_date_strings(self, mode, numDays) | Returns a tuple of start (in YYYY-MM-DD format) and end date
strings (in YYYY-MM-DD HH:MM:SS format for an inclusive day). | 2.713535 | 2.657152 | 1.021219 |
stockwell_text = re.search(r'\[stockwell (.+?)\]', whiteboard)
if stockwell_text is not None:
text = stockwell_text.group(1).split(':')[0]
if text == 'fixed' or text == 'disable-recommended' or text == 'infra' or text == 'disabled':
return True
r... | def check_whiteboard_status(self, whiteboard) | Extracts stockwell text from a bug's whiteboard status to
determine whether it matches specified stockwell text;
returns a boolean. | 6.55368 | 4.839516 | 1.354202 |
params = {'include_fields': 'product, component, priority, whiteboard, id'}
params['id'] = bug_ids
try:
response = self.session.get(settings.BZ_API_URL + '/rest/bug', headers=self.session.headers,
params=params, timeout=30)
... | def fetch_bug_details(self, bug_ids) | Fetches bug metadata from bugzilla and returns an encoded
dict if successful, otherwise returns None. | 3.524623 | 3.057847 | 1.152649 |
# Min required failures per bug in order to post a comment
threshold = 1 if self.weekly_mode else 15
bug_ids = (BugJobMap.failures.by_date(startday, endday)
.values('bug_id')
.annotate(total=Count('bug_id'))
... | def get_bug_stats(self, startday, endday) | Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
"1206327": {
"total": 5,
"per_repos... | 2.559826 | 2.368881 | 1.080606 |
bugs = (BugJobMap.failures.by_date(startday, endday)
.filter(bug_id__in=bug_ids)
.values('bug_id')
.annotate(total=Count('id'))
.values('bug_id', 'total'))
re... | def get_alt_date_bug_totals(self, startday, endday, bug_ids) | use previously fetched bug_ids to check for total failures
exceeding 150 in 21 days | 3.60102 | 3.252485 | 1.107159 |
min = 0
max = 600
bugs_list = []
bug_ids_length = len(bug_ids)
while bug_ids_length >= min and bug_ids_length > 0:
data = self.fetch_bug_details(bug_ids[min:max])
if data:
bugs_list += data
min = max
max = ... | def fetch_all_bug_details(self, bug_ids) | batch requests for bugzilla data in groups of 1200 (which is the safe
limit for not hitting the max url length) | 2.84147 | 2.750964 | 1.0329 |
'''
A lot of these transformations are from tasks before task labels and some of them are if we
grab data directly from Treeherder jobs endpoint instead of runnable jobs API.
'''
# XXX: Evaluate which of these transformations are still valid
if testtype.startswith('[funsize'):
return Non... | def transform(testtype) | A lot of these transformations are from tasks before task labels and some of them are if we
grab data directly from Treeherder jobs endpoint instead of runnable jobs API. | 9.875319 | 6.230085 | 1.585102 |
subject = user_info['sub']
email = user_info['email']
if "Mozilla-LDAP" in subject:
return "mozilla-ldap/" + email
elif "email" in subject:
return "email/" + email
elif "github" in subject:
return "github/" + email
elif "goog... | def _get_username_from_userinfo(self, user_info) | Get the user's username from the jwt sub property | 3.742995 | 3.52999 | 1.060341 |
# JWT Validator
# Per https://auth0.com/docs/quickstart/backend/python/01-authorization#create-the-jwt-validation-decorator
try:
unverified_header = jwt.get_unverified_header(id_token)
except jwt.JWTError:
raise AuthError('Unable to decode the Id token ... | def _get_user_info(self, access_token, id_token) | Extracts the user info payload from the Id Token.
Example return value:
{
"at_hash": "<HASH>",
"aud": "<HASH>",
"email_verified": true,
"email": "fsurname@mozilla.com",
"exp": 1551259495,
"family_name": "Surname",
"giv... | 2.573336 | 2.497782 | 1.030248 |
access_token_expiry_timestamp = self._get_access_token_expiry(request)
id_token_expiry_timestamp = self._get_id_token_expiry(user_info)
now_in_seconds = int(time.time())
# The session length is set to match whichever token expiration time is closer.
earliest_expiration_... | def _calculate_session_expiry(self, request, user_info) | Returns the number of seconds after which the Django session should expire. | 3.003227 | 2.884582 | 1.041131 |
return unique_key(testtype=str(job['testtype']),
buildtype=str(job['platform_option']),
platform=str(job['platform'])) | def _unique_key(job) | Return a key to query our uniqueness mapping system.
This makes sure that we use a consistent key between our code and selecting jobs from the
table. | 10.064597 | 12.154963 | 0.828024 |
job_build_system_type = {}
sanitized_list = []
for job in runnable_jobs_data:
if not valid_platform(job['platform']):
logger.info('Invalid platform %s', job['platform'])
continue
testtype = parse_testtype(
build_system_type=job['build_system_type'],
... | def _sanitize_data(runnable_jobs_data) | We receive data from runnable jobs api and return the sanitized data that meets our needs.
This is a loop to remove duplicates (including buildsystem -> * transformations if needed)
By doing this, it allows us to have a single database query
It returns sanitized_list which will contain a subset which excl... | 3.652459 | 2.985456 | 1.223417 |
jp_index, priority, expiration_date = _initialize_values()
total_jobs = len(data)
new_jobs, failed_changes, updated_jobs = 0, 0, 0
# Loop through sanitized jobs, add new jobs and update the build system if needed
for job in data:
key = _unique_key(job)
if key in jp_index:
... | def _update_table(data) | Add new jobs to the priority table and update the build system if required.
data - it is a list of dictionaries that describe a job type
returns the number of new, failed and updated jobs | 3.691609 | 3.462925 | 1.066038 |
if not JobPriority.objects.exists():
return
preseed = preseed_data()
for job in preseed:
queryset = JobPriority.objects.all()
for field in ('testtype', 'buildtype', 'platform'):
if job[field] != '*':
queryset = queryset.filter(**{field: job[field]})... | def load_preseed() | Update JobPriority information from preseed.json
The preseed data has these fields: buildtype, testtype, platform, priority, expiration_date
The expiration_date field defaults to 2 weeks when inserted in the table
The expiration_date field has the format "YYYY-MM-DD", however, it can have "*" to indicate t... | 7.102615 | 5.004345 | 1.41929 |
'''
Helper method to return all possible valid time intervals for data
stored by Perfherder
'''
return [PerformanceTimeInterval.DAY,
PerformanceTimeInterval.WEEK,
PerformanceTimeInterval.TWO_WEEKS,
PerformanceTimeInterval.SIXTY_DAYS... | def all_valid_time_intervals() | Helper method to return all possible valid time intervals for data
stored by Perfherder | 6.779343 | 2.964559 | 2.286796 |
'''
Returns a filtered subset of this collection of signatures, based on
a set of key/value tuples
This is useful when you only want a subset of the signatures in a project.
Example usage:
::
pc = PerfherderClient()
signatures = pc.get_signature... | def filter(self, *args) | Returns a filtered subset of this collection of signatures, based on
a set of key/value tuples
This is useful when you only want a subset of the signatures in a project.
Example usage:
::
pc = PerfherderClient()
signatures = pc.get_signatures('mozilla-central')... | 6.074154 | 1.659515 | 3.660199 |
'''
Returns all property names in this collection of signatures
'''
property_names = set()
for signature_value in self.values():
for property_name in signature_value.keys():
property_names.add(property_name)
return property_names | def get_property_names(self) | Returns all property names in this collection of signatures | 4.321405 | 2.642781 | 1.635173 |
'''
Returns all property values for a particular property name in this collection
'''
property_values = set()
for signature_value in self.values():
if signature_value.get(property_name):
property_values.add(signature_value[property_name])
retur... | def get_property_values(self, property_name) | Returns all property values for a particular property name in this collection | 3.940799 | 2.817029 | 1.39892 |
'''
Gets a set of performance signatures associated with a project and time range
'''
results = self._get_json(self.PERFORMANCE_SIGNATURES_ENDPOINT, project, **params)
return PerformanceSignatureCollection(results) | def get_performance_signatures(self, project, **params) | Gets a set of performance signatures associated with a project and time range | 6.690293 | 5.427223 | 1.232729 |
'''
Gets a dictionary of PerformanceSeries objects
You can specify which signatures to get by passing signature to this function
'''
results = self._get_json(self.PERFORMANCE_DATA_ENDPOINT, project, **params)
return {k: PerformanceSeries(v) for k, v in results.items()} | def get_performance_data(self, project, **params) | Gets a dictionary of PerformanceSeries objects
You can specify which signatures to get by passing signature to this function | 8.801908 | 3.341377 | 2.634215 |
from . import matchers
def is_matcher_func(member):
return inspect.isfunction(member) and member.__name__.endswith("_matcher")
members = inspect.getmembers(matchers, is_matcher_func)
for name, func in members:
yield func | def get_matchers() | Get matcher functions from treeherder.autoclassify.matchers
We classify matchers as any function treeherder.autoclassify.matchers with
a name ending in _matcher. This is currently overkill but protects against
the unwarey engineer adding new functions to the matchers module that
shouldn't be treated a... | 3.535126 | 3.236061 | 1.092416 |
for text_log_error in errors:
matches = find_all_matches(text_log_error, matchers) # TextLogErrorMatch instances, unsaved!
best_match = first(matches, key=lambda m: (-m.score, -m.classified_failure_id))
if not best_match:
continue
newrelic.agent.record_custom_even... | def find_best_matches(errors, matchers) | Find the best match for each error
We use the Good Enough™ ratio as a watershed level for match scores. | 5.276407 | 5.491186 | 0.960887 |
for matcher_func in matchers:
matches = matcher_func(text_log_error)
# matches: iterator of (score, ClassifiedFailure.id)
if not matches:
continue
for score, classified_failure_id in matches:
yield TextLogErrorMatch(
score=score,
... | def find_all_matches(text_log_error, matchers) | Find matches for the given error using the given matcher classes
Returns *unsaved* TextLogErrorMatch instances. | 3.474066 | 3.287342 | 1.056801 |
score_cut_off = 0.7
return (text_log_error.matches.filter(score__gt=score_cut_off)
.order_by("-score", "-classified_failure_id")
.select_related('classified_failure')
.first()) | def get_best_match(text_log_error) | Get the best TextLogErrorMatch for a given TextLogErrorMatch.
Matches are further filtered by the score cut off. | 6.527027 | 4.64353 | 1.405617 |
text_log_error.metadata.best_classification = classified_failure
text_log_error.metadata.save(update_fields=['best_classification'])
text_log_error.metadata.failure_line.elastic_search_insert() | def mark_best_classification(text_log_error, classified_failure) | Wrapper for setting best_classification on both TextLogError and FailureLine.
Set the given ClassifiedFailure as best_classification for the given
TextLogError. Handles the duplication of best_classification on FailureLine
so you don't have to! | 5.405962 | 4.66382 | 1.159127 |
for text_log_error in errors:
best_match = get_best_match(text_log_error)
if not best_match:
continue
mark_best_classification(text_log_error, best_match.classified_failure) | def mark_best_classifications(errors) | Convenience wrapper around mark_best_classification.
Finds the best match for each TextLogError in errors, handling no match
meeting the cut off score and then mark_best_classification to save that
information. | 4.420884 | 3.057552 | 1.44589 |
for match in matches:
try:
match.save()
except IntegrityError:
args = (match.text_log_error_id, match.matcher_name, match.classified_failure_id)
logger.warning(
"Tried to create duplicate match for TextLogError %i with matcher %s and classifie... | def update_db(matches) | Save TextLogErrorMatch instances to the DB
We loop each Match instance instead of calling bulk_create() so we can
catch any potential IntegrityErrors and continue. | 7.119721 | 4.737544 | 1.502829 |
file_path = os.path.join("schemas", filename)
with open(file_path) as f:
schema = yaml.load(f)
return schema | def get_json_schema(filename) | Get a JSON Schema by filename. | 2.7546 | 2.556231 | 1.077602 |
headers = headers or {}
headers['User-Agent'] = 'treeherder/{}'.format(settings.SITE_HOSTNAME)
# Work around bug 1305768.
if 'queue.taskcluster.net' in url:
headers['x-taskcluster-skip-cache'] = 'true'
response = requests.request(method,
url,
... | def make_request(url, method='GET', headers=None, timeout=30, **kwargs) | A wrapper around requests to set defaults & call raise_for_status(). | 4.015986 | 3.975062 | 1.010295 |
job_details = json.loads(job_info_artifact['blob'])['job_details']
for job_detail in job_details:
job_detail_dict = {
'title': job_detail.get('title'),
'value': job_detail['value'],
'url': job_detail.get('url')
}
for (k, v) in job_detail_dict.item... | def store_job_info_artifact(job, job_info_artifact) | Store the contents of the job info artifact
in job details | 3.208526 | 3.143541 | 1.020673 |
step_data = json.loads(
text_log_summary_artifact['blob'])['step_data']
result_map = {v: k for (k, v) in TextLogStep.RESULTS}
with transaction.atomic():
for step in step_data['steps']:
name = step['name'][:TextLogStep._meta.get_field('name').max_length]
# process... | def store_text_log_summary_artifact(job, text_log_summary_artifact) | Store the contents of the text log summary artifact | 5.146551 | 5.118269 | 1.005526 |
for artifact in artifact_data:
# Determine what type of artifact we have received
if artifact:
artifact_name = artifact.get('name')
if not artifact_name:
logger.error("load_job_artifacts: Unnamed job artifact, skipping")
continue
... | def store_job_artifacts(artifact_data) | Store a list of job artifacts. All of the datums in artifact_data need
to be in the following format:
{
'type': 'json',
'name': 'my-artifact-name',
# blob can be any kind of structured data
'blob': { 'stuff': [1, 2, 3, 4, 5] },
'job_guid': 'd22c74... | 3.087538 | 3.023197 | 1.021282 |
for artifact in artifacts:
blob = artifact['blob']
if (artifact['type'].lower() == 'json' and
not isinstance(blob, str)):
artifact['blob'] = json.dumps(blob)
return artifacts | def serialize_artifact_json_blobs(artifacts) | Ensure that JSON artifact blobs passed as dicts are converted to JSON | 3.425543 | 2.977386 | 1.15052 |
resp = self._get_json(self.OPTION_COLLECTION_HASH_ENDPOINT)
ret = {}
for result in resp:
ret[result['option_collection_hash']] = result['options']
return ret | def get_option_collection_hash(self) | Gets option collection hash, a mapping of hash values to build properties
Returns a dictionary with the following structure:
{
hashkey1: [ { key: value }, { key: value }, ... ],
hashkey2: [ { key: value }, { key: value }, ... ],
...
} | 5.097984 | 4.86232 | 1.048467 |
return self._get_json_list(self.PUSH_ENDPOINT, project, **params) | def get_pushes(self, project, **params) | Gets pushes from project, filtered by parameters
By default this method will just return the latest 10 pushes (if they exist)
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results | 7.298689 | 12.544583 | 0.58182 |
return self._get_json_list(self.JOBS_ENDPOINT, project, **params) | def get_jobs(self, project, **params) | Gets jobs from project, filtered by parameters
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results | 7.234625 | 10.394057 | 0.696035 |
return self._get_json(self.JOB_LOG_URL_ENDPOINT, project,
**params) | def get_job_log_url(self, project, **params) | Gets job log url, filtered by parameters
:param project: project (repository name) to query data for
:param params: keyword arguments to filter results | 9.23096 | 10.529729 | 0.876657 |
query = {
'query': {
'match_all': {}
}
}
for result in raw_query(query, index=index):
yield result | def all_documents(index=INDEX_NAME) | Get all documents from the given index.
Returns full Elasticsearch objects so you can get metadata too. | 3.439988 | 4.085732 | 0.841951 |
actions = compact(dict_to_op(
to_dict(model),
index_name=INDEX_NAME,
doc_type=DOC_TYPE,
op_type=action,
) for model in iterable)
# fail fast if there are no actions
if not actions:
return 0
items, _ = es_bulk(es_conn, actions, doc_type=doc_type, index=i... | def bulk(iterable, index=INDEX_NAME, doc_type=DOC_TYPE, action='index') | Wrapper of elasticsearch's bulk method
Converts an interable of models to document operations and submits them to
Elasticsearch. Returns a count of operations when done.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.bulk
https://www.elastic.co/guide/en/elastic... | 5.042525 | 5.035824 | 1.001331 |
refresh_index() # Refresh the index so we can get a correct count
query = {
'query': {
'match_all': {}
}
}
result = es_conn.count(index=index, doc_type=DOC_TYPE, body=query)
return result['count'] | def count_index(index=INDEX_NAME) | Return a document count for the given index.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.count
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-count.html | 3.431998 | 4.029686 | 0.851679 |
result = es_conn.get(index=index, doc_type=doc_type, id=id, **kwargs)
return result['_source'] | def get_document(id, index=INDEX_NAME, doc_type=DOC_TYPE, **kwargs) | Thin wrapper to get a single document by ID.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.get
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html | 2.381536 | 2.648418 | 0.89923 |
doc = to_dict(obj)
if doc is None:
return
id = doc.pop('id')
return es_conn.index(index, doc_type, doc, id=id) | def index(obj, index=INDEX_NAME, doc_type=DOC_TYPE) | Index the given document.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.index
https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html | 4.289249 | 4.834901 | 0.887143 |
result = es_conn.search(index=index, doc_type=DOC_TYPE, body=query)
return result['hits']['hits'] | def raw_query(query, index=INDEX_NAME, doc_type=DOC_TYPE) | Thin wrapper of the search function to provide useful defaults
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.search
http://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html | 2.661195 | 2.892717 | 0.919964 |
es_conn.indices.delete(index, ignore=404)
try:
es_conn.indices.create(index, INDEX_SETTINGS.get(index, None))
except TransportError as e:
raise Exception('Failed to created index, got: {}'.format(e.error)) | def reinit_index(index=INDEX_NAME) | Delete and then initialise the given index name
Gets settings if they exist in the mappings module.
https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.client.IndicesClient.create
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
https://el... | 4.123706 | 4.664145 | 0.884129 |
results = raw_query(query, index=index, doc_type=doc_type)
return [r['_source'] for r in results] | def search(query, index=INDEX_NAME, doc_type=DOC_TYPE) | Thin wrapper of the main query function to provide just the resulting objects | 2.971991 | 2.784519 | 1.067327 |
'''Set the expiration date of every job that has expired.'''
# Only select rows where there is an expiration date set
for job in JobPriority.objects.filter(expiration_date__isnull=False):
if job.has_expired():
job.expiration_date = None
job.save() | def clear_expiration_field_for_expired_jobs(self) | Set the expiration date of every job that has expired. | 5.914834 | 4.895511 | 1.208216 |
# Only job priorities that don't have an expiration date (2 weeks for new jobs or year 2100
# for jobs update via load_preseed) are updated
for jp in JobPriority.objects.filter(expiration_date__isnull=True):
if jp.unique_identifier() not in high_value_jobs:
i... | def adjust_jobs_priority(self, high_value_jobs, priority=1) | For every job priority determine if we need to increase or decrease the job priority
Currently, high value jobs have a priority of 1 and a timeout of 0. | 4.938 | 4.801813 | 1.028361 |
try:
report = json.loads(request.body)['csp-report']
except (KeyError, TypeError, ValueError):
return HttpResponseBadRequest('Invalid CSP violation report')
logger.warning('CSP violation: %s', report)
newrelic.agent.record_custom_event('CSP violation', report)
return HttpRespon... | def csp_report_collector(request) | Accepts the Content-Security-Policy violation reports generated via the `report-uri` feature:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri
This is written as a standard Django view rather than as a django-rest-framework APIView,
since the latter ends up being... | 3.663709 | 3.752913 | 0.976231 |
''' Routing to /api/project/{project}/seta/job-priorities/
This API can potentially have these consumers:
* Buildbot
* build_system_type=buildbot
* priority=5
* format=json
* TaskCluster (Gecko decision task)
* build_system... | def list(self, request, project) | Routing to /api/project/{project}/seta/job-priorities/
This API can potentially have these consumers:
* Buildbot
* build_system_type=buildbot
* priority=5
* format=json
* TaskCluster (Gecko decision task)
* build_system_type=taskcl... | 7.652375 | 1.968192 | 3.888022 |
'''
custom method to serialize + format jobs information
It's worth doing this big ugly thing (as opposed to using
the django rest framework serializer or whatever) as
this function is often in the critical path
'''
option_collection_map = OptionCollection.object... | def _get_job_list_response(self, job_qs, offset, count, return_type) | custom method to serialize + format jobs information
It's worth doing this big ugly thing (as opposed to using
the django rest framework serializer or whatever) as
this function is often in the critical path | 4.499527 | 2.992344 | 1.50368 |
try:
job = Job.objects.select_related(
*self._default_select_related + ['taskcluster_metadata']).get(
repository__name=project, id=pk)
except Job.DoesNotExist:
return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND... | def retrieve(self, request, project, pk=None) | GET method implementation for detail view
Return a single job with log_references and
artifact names and links to the artifact blobs. | 2.94743 | 2.891133 | 1.019472 |
MAX_JOBS_COUNT = 2000
# make a mutable copy of these params
filter_params = request.query_params.copy()
# various hacks to ensure API backwards compatibility
for param_key in filter_params.keys():
# replace `result_set_id` with `push_id`
if para... | def list(self, request, project) | GET method implementation for list view
Optional parameters (default):
- offset (0)
- count (10)
- return_type (dict) | 2.646385 | 2.576164 | 1.027258 |
try:
job = Job.objects.get(repository__name=project,
id=pk)
except ObjectDoesNotExist:
return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
textlog_steps = TextLogStep.objects.filter(job=job).order_by(
... | def text_log_steps(self, request, project, pk=None) | Gets a list of steps associated with this job | 3.378607 | 3.240114 | 1.042743 |
try:
job = Job.objects.get(repository__name=project,
id=pk)
except Job.DoesNotExist:
return Response("No job with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND)
textlog_errors = (TextLogError.objects
... | def text_log_errors(self, request, project, pk=None) | Gets a list of steps associated with this job | 4.327862 | 3.917022 | 1.104886 |
try:
job = Job.objects.get(repository__name=project, id=pk)
except ObjectDoesNotExist:
return Response("No job with id: {0}".format(pk), status=HTTP_404_NOT_FOUND)
return Response(get_error_summary(job)) | def bug_suggestions(self, request, project, pk=None) | Gets a set of bug suggestions for this job | 3.751872 | 3.413789 | 1.099035 |
try:
repository = Repository.objects.get(name=project)
except Repository.DoesNotExist:
return Response({
"detail": "No project with name {}".format(project)
}, status=HTTP_404_NOT_FOUND)
try:
job = Job.objects.get(reposito... | def similar_jobs(self, request, project, pk=None) | Get a list of jobs similar to the one selected. | 3.055312 | 3.04452 | 1.003545 |
logger.debug("Crossreference %s: started", job.id)
if job.autoclassify_status >= Job.CROSSREFERENCED:
logger.info("Job %i already crossreferenced", job.id)
return False
try:
rv = _crossreference(job)
except IntegrityError:
job.autoclassify_status = Job.FAILED
... | def crossreference_job(job) | Try to match the unstructured error lines with the corresponding structured error
lines, relying on the fact that serialization of mozlog (and hence errorsummary files)
is determinisic so we can reserialize each structured error line and perform an in-order
textual match.
:job: - Job for which to perfo... | 3.492698 | 3.47434 | 1.005284 |
summary = partial(failure_line_summary, TbplFormatter())
for failure_line in failure_lines:
repr_str = summary(failure_line)
if repr_str:
yield failure_line, repr_str
while True:
yield None, None | def structured_iterator(failure_lines) | Create FailureLine, Tbpl-formatted-string tuples. | 6.423127 | 4.340936 | 1.479664 |
if failure_line.action == "test_result":
action = "test_status" if failure_line.subtest is not None else "test_end"
elif failure_line.action == "truncated":
return
else:
action = failure_line.action
try:
mozlog_func = getattr(formatter, action)
except AttributeE... | def failure_line_summary(formatter, failure_line) | Create a mozlog formatted error summary string from the given failure_line.
Create a string which can be compared to a TextLogError.line string to see
if they match. | 4.061197 | 3.818825 | 1.063468 |
url = furl(redis_url)
url.port += 1
url.scheme += 's'
# Disable TLS certificate validation (restoring the behaviour of the older redis-py 2.x),
# since for now Heroku Redis uses self-signed certificates:
# https://bugzilla.mozilla.org/show_bug.cgi?id=1510000
url.args['ssl_cert_reqs'] = ... | def get_tls_redis_url(redis_url) | Returns the TLS version of a Heroku REDIS_URL string.
Whilst Redis server (like memcached) doesn't natively support TLS, Heroku runs an stunnel
daemon on their Redis instances, which can be connected to directly by Redis clients that
support TLS (avoiding the need for stunnel on the client). The stunnel po... | 5.828296 | 5.758591 | 1.012105 |
with make_request(self.url, stream=True) as response:
download_size_in_bytes = int(response.headers.get('Content-Length', -1))
# Temporary annotation of log size to help set thresholds in bug 1295997.
newrelic.agent.add_custom_parameter(
'unstructure... | def parse(self) | Iterate over each line of the log, running each parser against it.
Stream lines from the gzip file and run each parser against it,
building the ``artifact`` as we go. | 6.732206 | 6.400601 | 1.051808 |
'''
Gets a summary of what passed/failed for the push
'''
jobs = Job.objects.filter(push=self).filter(
Q(failure_classification__isnull=True) |
Q(failure_classification__name='not classified')).exclude(tier=3)
status_dict = {}
for (state, result, ... | def get_status(self) | Gets a summary of what passed/failed for the push | 5.94355 | 4.643053 | 1.280095 |
options = sorted(list(options))
sha_hash = sha1()
# equivalent to loop over the options and call sha_hash.update()
sha_hash.update(''.join(options).encode('utf-8'))
return sha_hash.hexdigest() | def calculate_hash(options) | returns an option_collection_hash given a list of options | 4.61522 | 4.142479 | 1.11412 |
# Retrieve list of jobs to delete
jobs_max_timestamp = datetime.datetime.now() - cycle_interval
jobs_cycled = 0
while True:
jobs_chunk = list(self.filter(repository=repository, submit_time__lt=jobs_max_timestamp)
.values_list('guid... | def cycle_data(self, repository, cycle_interval, chunk_size, sleep_time) | Delete data older than cycle_interval, splitting the target data into
chunks of chunk_size size. Returns the number of result sets deleted | 6.955956 | 6.860084 | 1.013975 |
if FailureLine.objects.filter(job_guid=self.guid,
action="truncated").count() > 0:
return False
classified_error_count = TextLogError.objects.filter(
_metadata__best_classification__isnull=False,
step__job=self).count()
... | def is_fully_autoclassified(self) | Returns whether a job is fully autoclassified (i.e. we have
classification information for all failure lines) | 8.939213 | 7.331954 | 1.219213 |
unverified_errors = TextLogError.objects.filter(
_metadata__best_is_verified=False,
step__job=self).count()
if unverified_errors:
logger.error("Job %r has unverified TextLogErrors", self)
return False
logger.info("Job %r is fully verifie... | def is_fully_verified(self) | Determine if this Job is fully verified based on the state of its Errors.
An Error (TextLogError or FailureLine) is considered Verified once its
related TextLogErrorMetadata has best_is_verified set to True. A Job
is then considered Verified once all its Errors TextLogErrorMetadata
ins... | 6.904137 | 3.746223 | 1.842959 |
if not self.is_fully_verified():
return
classification = 'autoclassified intermittent'
already_classified = (JobNote.objects.filter(job=self)
.exclude(failure_classification__name=classification)
... | def update_after_verification(self, user) | Updates a job's state after being verified by a sheriff | 8.178568 | 7.709654 | 1.060822 |
try:
text_log_error = TextLogError.objects.get(step__job=self)
except (TextLogError.DoesNotExist, TextLogError.MultipleObjectsReturned):
return None
# Can this TextLogError be converted into a single "useful search"?
# FIXME: what is the significance of ... | def get_manual_classification_line(self) | If this Job has a single TextLogError line, return that TextLogError.
Some Jobs only have one related [via TextLogStep] TextLogError. This
method checks if this Job is one of those (returning None if not) by:
* checking the number of related TextLogErrors
* counting the number of searc... | 6.564936 | 4.048279 | 1.621661 |
# update the job classification
note = JobNote.objects.filter(job=self.job).order_by('-created').first()
if note:
self.job.failure_classification_id = note.failure_classification.id
else:
self.job.failure_classification_id = FailureClassification.objects.... | def _update_failure_type(self) | Updates the failure type of this Note's Job.
Set the linked Job's failure type to that of the most recent JobNote or
set to Not Classified if there are no JobNotes.
This is called when JobNotes are created (via .save()) and deleted (via
.delete()) and is used to resolved the FailureCla... | 3.529579 | 2.561791 | 1.377778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.