blob: 32f7bc01e8ad94977cd49855a77fa153453042c6 [file] [log] [blame]
Adele Zhoubf3b7692016-08-11 18:45:18 -07001#!/usr/bin/env python2.7
2# Copyright 2016, Google Inc.
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31"""Tool to get build statistics from Jenkins and upload to BigQuery."""
32
33import argparse
34import jenkinsapi
35from jenkinsapi.custom_exceptions import JenkinsAPIException
36from jenkinsapi.jenkins import Jenkins
37import json
38import os
39import re
40import sys
41import urllib
42
43
44gcp_utils_dir = os.path.abspath(os.path.join(
45 os.path.dirname(__file__), '../gcp/utils'))
46sys.path.append(gcp_utils_dir)
47import big_query_utils
48
49
50_HAS_MATRIX=True
51_PROJECT_ID = 'grpc-testing'
52_HAS_MATRIX = True
53_BUILDS = {'gRPC_master': _HAS_MATRIX,
54 'gRPC_interop_master': not _HAS_MATRIX,
55 'gRPC_pull_requests': _HAS_MATRIX,
56 'gRPC_interop_pull_requests': not _HAS_MATRIX,
57}
58_URL_BASE = 'https://grpc-testing.appspot.com/job'
Adele Zhou445534e2016-09-06 17:57:11 -070059
60# This is a dynamic list where known and active issues should be added.
61# Fixed ones should be removed.
62# Also try not to add multiple messages from the same failure.
Adele Zhoubf3b7692016-08-11 18:45:18 -070063_KNOWN_ERRORS = [
64 'Failed to build workspace Tests with scheme AllTests',
65 'Build timed out',
Adele Zhou859d2a42016-09-16 15:15:44 -070066 'TIMEOUT: tools/run_tests/pre_build_node.sh',
67 'TIMEOUT: tools/run_tests/pre_build_ruby.sh',
Adele Zhoubf3b7692016-08-11 18:45:18 -070068 'FATAL: Unable to produce a script file',
Adele Zhou107e51e2016-09-08 11:37:30 -070069 'FAILED: build_docker_c\+\+',
Adele Zhou445534e2016-09-06 17:57:11 -070070 'cannot find package \"cloud.google.com/go/compute/metadata\"',
Adele Zhoubf3b7692016-08-11 18:45:18 -070071 'LLVM ERROR: IO failure on output stream.',
72 'MSBUILD : error MSB1009: Project file does not exist.',
Adele Zhou445534e2016-09-06 17:57:11 -070073 'fatal: git fetch_pack: expected ACK/NAK',
74 'Failed to fetch from http://github.com/grpc/grpc.git',
75 ('hudson.remoting.RemotingSystemException: java.io.IOException: '
76 'Backing channel is disconnected.'),
Adele Zhou107e51e2016-09-08 11:37:30 -070077 'hudson.remoting.ChannelClosedException',
Adele Zhou59af64b2016-09-22 15:23:54 -070078 'Could not initialize class hudson.Util',
79 'Too many open files in system',
Adele Zhou445534e2016-09-06 17:57:11 -070080 'FAILED: bins/tsan/qps_openloop_test GRPC_POLL_STRATEGY=epoll',
81 'FAILED: bins/tsan/qps_openloop_test GRPC_POLL_STRATEGY=legacy',
82 'FAILED: bins/tsan/qps_openloop_test GRPC_POLL_STRATEGY=poll',
83 ('tests.bins/asan/h2_proxy_test streaming_error_response '
84 'GRPC_POLL_STRATEGY=legacy'),
Adele Zhoubf3b7692016-08-11 18:45:18 -070085]
86_UNKNOWN_ERROR = 'Unknown error'
87_DATASET_ID = 'build_statistics'
88
89
90def _scrape_for_known_errors(html):
91 error_list = []
92 known_error_count = 0
93 for known_error in _KNOWN_ERRORS:
94 errors = re.findall(known_error, html)
95 this_error_count = len(errors)
96 if this_error_count > 0:
97 known_error_count += this_error_count
98 error_list.append({'description': known_error,
99 'count': this_error_count})
100 print('====> %d failures due to %s' % (this_error_count, known_error))
101 return error_list, known_error_count
102
103
104def _get_last_processed_buildnumber(build_name):
105 query = 'SELECT max(build_number) FROM [%s:%s.%s];' % (
106 _PROJECT_ID, _DATASET_ID, build_name)
107 query_job = big_query_utils.sync_query_job(bq, _PROJECT_ID, query)
108 page = bq.jobs().getQueryResults(
109 pageToken=None,
110 **query_job['jobReference']).execute(num_retries=3)
111 if page['rows'][0]['f'][0]['v']:
112 return int(page['rows'][0]['f'][0]['v'])
113 return 0
114
115
116def _process_matrix(build, url_base):
117 matrix_list = []
118 for matrix in build.get_matrix_runs():
119 matrix_str = re.match('.*\\xc2\\xbb ((?:[^,]+,?)+) #.*',
120 matrix.name).groups()[0]
121 matrix_tuple = matrix_str.split(',')
122 json_url = '%s/config=%s,language=%s,platform=%s/testReport/api/json' % (
123 url_base, matrix_tuple[0], matrix_tuple[1], matrix_tuple[2])
124 console_url = '%s/config=%s,language=%s,platform=%s/consoleFull' % (
125 url_base, matrix_tuple[0], matrix_tuple[1], matrix_tuple[2])
126 matrix_dict = {'name': matrix_str,
127 'duration': matrix.get_duration().total_seconds()}
128 matrix_dict.update(_process_build(json_url, console_url))
129 matrix_list.append(matrix_dict)
130
131 return matrix_list
132
133
134def _process_build(json_url, console_url):
135 build_result = {}
136 error_list = []
137 try:
138 html = urllib.urlopen(json_url).read()
139 test_result = json.loads(html)
140 print('====> Parsing result from %s' % json_url)
141 failure_count = test_result['failCount']
142 build_result['pass_count'] = test_result['passCount']
143 build_result['failure_count'] = failure_count
144 if failure_count > 0:
145 error_list, known_error_count = _scrape_for_known_errors(html)
146 unknown_error_count = failure_count - known_error_count
147 # This can happen if the same error occurs multiple times in one test.
148 if failure_count < known_error_count:
149 print('====> Some errors are duplicates.')
150 unknown_error_count = 0
151 error_list.append({'description': _UNKNOWN_ERROR,
152 'count': unknown_error_count})
153 except Exception as e:
154 print('====> Got exception for %s: %s.' % (json_url, str(e)))
155 print('====> Parsing errors from %s.' % console_url)
156 html = urllib.urlopen(console_url).read()
157 build_result['pass_count'] = 0
158 build_result['failure_count'] = 1
159 error_list, _ = _scrape_for_known_errors(html)
160 if error_list:
161 error_list.append({'description': _UNKNOWN_ERROR, 'count': 0})
162 else:
163 error_list.append({'description': _UNKNOWN_ERROR, 'count': 1})
164
165 if error_list:
166 build_result['error'] = error_list
167
168 return build_result
169
170
171# parse command line
172argp = argparse.ArgumentParser(description='Get build statistics.')
173argp.add_argument('-u', '--username', default='jenkins')
174argp.add_argument('-b', '--builds',
175 choices=['all'] + sorted(_BUILDS.keys()),
176 nargs='+',
177 default=['all'])
178args = argp.parse_args()
179
180J = Jenkins('https://grpc-testing.appspot.com', args.username, 'apiToken')
181bq = big_query_utils.create_big_query()
182
183for build_name in _BUILDS.keys() if 'all' in args.builds else args.builds:
184 print('====> Build: %s' % build_name)
185 # Since get_last_completed_build() always fails due to malformatted string
186 # error, we use get_build_metadata() instead.
187 job = None
188 try:
189 job = J[build_name]
190 except Exception as e:
191 print('====> Failed to get build %s: %s.' % (build_name, str(e)))
192 continue
193 last_processed_build_number = _get_last_processed_buildnumber(build_name)
194 last_complete_build_number = job.get_last_completed_buildnumber()
195 # To avoid processing all builds for a project never looked at. In this case,
196 # only examine 10 latest builds.
197 starting_build_number = max(last_processed_build_number+1,
198 last_complete_build_number-9)
199 for build_number in xrange(starting_build_number,
200 last_complete_build_number+1):
201 print('====> Processing %s build %d.' % (build_name, build_number))
202 build = None
203 try:
204 build = job.get_build_metadata(build_number)
205 except KeyError:
206 print('====> Build %s is missing. Skip.' % build_number)
207 continue
208 build_result = {'build_number': build_number,
209 'timestamp': str(build.get_timestamp())}
210 url_base = json_url = '%s/%s/%d' % (_URL_BASE, build_name, build_number)
211 if _BUILDS[build_name]: # The build has matrix, such as gRPC_master.
212 build_result['matrix'] = _process_matrix(build, url_base)
213 else:
214 json_url = '%s/testReport/api/json' % url_base
215 console_url = '%s/consoleFull' % url_base
216 build_result['duration'] = build.get_duration().total_seconds()
217 build_result.update(_process_build(json_url, console_url))
218 rows = [big_query_utils.make_row(build_number, build_result)]
219 if not big_query_utils.insert_rows(bq, _PROJECT_ID, _DATASET_ID, build_name,
220 rows):
221 print '====> Error uploading result to bigquery.'
222 sys.exit(1)
223