• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright 2015 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Detect new flakes and create issues for them"""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import datetime
22import json
23import logging
24import os
25import pprint
26import sys
27import urllib
28import urllib2
29from collections import namedtuple
30
31gcp_utils_dir = os.path.abspath(
32    os.path.join(os.path.dirname(__file__), '../gcp/utils'))
33sys.path.append(gcp_utils_dir)
34
35import big_query_utils
36
37GH_ISSUE_CREATION_URL = 'https://api.github.com/repos/grpc/grpc/issues'
38GH_ISSUE_SEARCH_URL = 'https://api.github.com/search/issues'
39KOKORO_BASE_URL = 'https://kokoro2.corp.google.com/job/'
40
41
42def gh(url, data=None):
43    request = urllib2.Request(url, data=data)
44    assert TOKEN
45    request.add_header('Authorization', 'token {}'.format(TOKEN))
46    if data:
47        request.add_header('Content-type', 'application/json')
48    response = urllib2.urlopen(request)
49    if 200 <= response.getcode() < 300:
50        return json.loads(response.read())
51    else:
52        raise ValueError('Error ({}) accessing {}'.format(
53            response.getcode(), response.geturl()))
54
55
56def search_gh_issues(search_term, status='open'):
57    params = ' '.join((search_term, 'is:issue', 'is:open', 'repo:grpc/grpc'))
58    qargs = urllib.urlencode({'q': params})
59    url = '?'.join((GH_ISSUE_SEARCH_URL, qargs))
60    response = gh(url)
61    return response
62
63
64def create_gh_issue(title, body, labels, assignees=[]):
65    params = {'title': title, 'body': body, 'labels': labels}
66    if assignees:
67        params['assignees'] = assignees
68    data = json.dumps(params)
69    response = gh(GH_ISSUE_CREATION_URL, data)
70    issue_url = response['html_url']
71    print('Created issue {} for {}'.format(issue_url, title))
72
73
74def build_kokoro_url(job_name, build_id):
75    job_path = '{}/{}'.format('/job/'.join(job_name.split('/')), build_id)
76    return KOKORO_BASE_URL + job_path
77
78
79def create_issues(new_flakes, always_create):
80    for test_name, results_row in new_flakes.items():
81        poll_strategy, job_name, build_id, timestamp = results_row
82        # TODO(dgq): the Kokoro URL has a limited lifetime. The permanent and ideal
83        # URL would be the sponge one, but there's currently no easy way to retrieve
84        # it.
85        url = build_kokoro_url(job_name, build_id)
86        title = 'New Failure: ' + test_name
87        body = '- Test: {}\n- Poll Strategy: {}\n- URL: {}'.format(
88            test_name, poll_strategy, url)
89        labels = ['infra/New Failure']
90        if always_create:
91            proceed = True
92        else:
93            preexisting_issues = search_gh_issues(test_name)
94            if preexisting_issues['total_count'] > 0:
95                print('\nFound {} issues for "{}":'.format(
96                    preexisting_issues['total_count'], test_name))
97                for issue in preexisting_issues['items']:
98                    print('\t"{}" ; URL: {}'.format(issue['title'],
99                                                    issue['html_url']))
100            else:
101                print(
102                    '\nNo preexisting issues found for "{}"'.format(test_name))
103            proceed = raw_input(
104                'Create issue for:\nTitle: {}\nBody: {}\n[Y/n] '.format(
105                    title, body)) in ('y', 'Y', '')
106        if proceed:
107            assignees_str = raw_input(
108                'Asignees? (comma-separated, leave blank for unassigned): ')
109            assignees = [
110                assignee.strip() for assignee in assignees_str.split(',')
111            ]
112            create_gh_issue(title, body, labels, assignees)
113
114
115def print_table(table, format):
116    first_time = True
117    for test_name, results_row in table.items():
118        poll_strategy, job_name, build_id, timestamp = results_row
119        full_kokoro_url = build_kokoro_url(job_name, build_id)
120        if format == 'human':
121            print("\t- Test: {}, Polling: {}, Timestamp: {}, url: {}".format(
122                test_name, poll_strategy, timestamp, full_kokoro_url))
123        else:
124            assert (format == 'csv')
125            if first_time:
126                print('test,timestamp,url')
127                first_time = False
128            print("{},{},{}".format(test_name, timestamp, full_kokoro_url))
129
130
131Row = namedtuple('Row', ['poll_strategy', 'job_name', 'build_id', 'timestamp'])
132
133
134def get_new_failures(dates):
135    bq = big_query_utils.create_big_query()
136    this_script_path = os.path.join(os.path.dirname(__file__))
137    sql_script = os.path.join(this_script_path, 'sql/new_failures_24h.sql')
138    with open(sql_script) as query_file:
139        query = query_file.read().format(
140            calibration_begin=dates['calibration']['begin'],
141            calibration_end=dates['calibration']['end'],
142            reporting_begin=dates['reporting']['begin'],
143            reporting_end=dates['reporting']['end'])
144    logging.debug("Query:\n%s", query)
145    query_job = big_query_utils.sync_query_job(bq, 'grpc-testing', query)
146    page = bq.jobs().getQueryResults(
147        pageToken=None, **query_job['jobReference']).execute(num_retries=3)
148    rows = page.get('rows')
149    if rows:
150        return {
151            row['f'][0]['v']: Row(
152                poll_strategy=row['f'][1]['v'],
153                job_name=row['f'][2]['v'],
154                build_id=row['f'][3]['v'],
155                timestamp=row['f'][4]['v'])
156            for row in rows
157        }
158    else:
159        return {}
160
161
162def parse_isodate(date_str):
163    return datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
164
165
166def get_new_flakes(args):
167    """The from_date_str argument marks the beginning of the "calibration", used
168  to establish the set of pre-existing flakes, which extends over
169  "calibration_days".  After the calibration period, "reporting_days" is the
170  length of time during which new flakes will be reported.
171
172from
173date
174  |--------------------|---------------|
175  ^____________________^_______________^
176       calibration         reporting
177         days                days
178  """
179    dates = process_date_args(args)
180    new_failures = get_new_failures(dates)
181    logging.info('|new failures| = %d', len(new_failures))
182    return new_failures
183
184
185def build_args_parser():
186    import argparse, datetime
187    parser = argparse.ArgumentParser()
188    today = datetime.date.today()
189    a_week_ago = today - datetime.timedelta(days=7)
190    parser.add_argument(
191        '--calibration_days',
192        type=int,
193        default=7,
194        help='How many days to consider for pre-existing flakes.')
195    parser.add_argument(
196        '--reporting_days',
197        type=int,
198        default=1,
199        help='How many days to consider for the detection of new flakes.')
200    parser.add_argument(
201        '--count_only',
202        dest='count_only',
203        action='store_true',
204        help='Display only number of new flakes.')
205    parser.set_defaults(count_only=False)
206    parser.add_argument(
207        '--create_issues',
208        dest='create_issues',
209        action='store_true',
210        help='Create issues for all new flakes.')
211    parser.set_defaults(create_issues=False)
212    parser.add_argument(
213        '--always_create_issues',
214        dest='always_create_issues',
215        action='store_true',
216        help='Always create issues for all new flakes. Otherwise,'
217        ' interactively prompt for every issue.')
218    parser.set_defaults(always_create_issues=False)
219    parser.add_argument(
220        '--token',
221        type=str,
222        default='',
223        help='GitHub token to use its API with a higher rate limit')
224    parser.add_argument(
225        '--format',
226        type=str,
227        choices=['human', 'csv'],
228        default='human',
229        help='Output format: are you a human or a machine?')
230    parser.add_argument(
231        '--loglevel',
232        type=str,
233        choices=['INFO', 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL'],
234        default='WARNING',
235        help='Logging level.')
236    return parser
237
238
239def process_date_args(args):
240    calibration_begin = (
241        datetime.date.today() - datetime.timedelta(days=args.calibration_days) -
242        datetime.timedelta(days=args.reporting_days))
243    calibration_end = calibration_begin + datetime.timedelta(
244        days=args.calibration_days)
245    reporting_begin = calibration_end
246    reporting_end = reporting_begin + datetime.timedelta(
247        days=args.reporting_days)
248    return {
249        'calibration': {
250            'begin': calibration_begin,
251            'end': calibration_end
252        },
253        'reporting': {
254            'begin': reporting_begin,
255            'end': reporting_end
256        }
257    }
258
259
260def main():
261    global TOKEN
262    args_parser = build_args_parser()
263    args = args_parser.parse_args()
264    if args.create_issues and not args.token:
265        raise ValueError(
266            'Missing --token argument, needed to create GitHub issues')
267    TOKEN = args.token
268
269    logging_level = getattr(logging, args.loglevel)
270    logging.basicConfig(format='%(asctime)s %(message)s', level=logging_level)
271    new_flakes = get_new_flakes(args)
272
273    dates = process_date_args(args)
274
275    dates_info_string = 'from {} until {} (calibrated from {} until {})'.format(
276        dates['reporting']['begin'].isoformat(),
277        dates['reporting']['end'].isoformat(),
278        dates['calibration']['begin'].isoformat(),
279        dates['calibration']['end'].isoformat())
280
281    if args.format == 'human':
282        if args.count_only:
283            print(len(new_flakes), dates_info_string)
284        elif new_flakes:
285            found_msg = 'Found {} new flakes {}'.format(
286                len(new_flakes), dates_info_string)
287            print(found_msg)
288            print('*' * len(found_msg))
289            print_table(new_flakes, 'human')
290            if args.create_issues:
291                create_issues(new_flakes, args.always_create_issues)
292        else:
293            print('No new flakes found '.format(len(new_flakes)),
294                  dates_info_string)
295    elif args.format == 'csv':
296        if args.count_only:
297            print('from_date,to_date,count')
298            print('{},{},{}'.format(dates['reporting']['begin'].isoformat(),
299                                    dates['reporting']['end'].isoformat(),
300                                    len(new_flakes)))
301        else:
302            print_table(new_flakes, 'csv')
303    else:
304        raise ValueError('Invalid argument for --format: {}'.format(
305            args.format))
306
307
308if __name__ == '__main__':
309    main()
310