1#!/usr/bin/env python
2# Copyright 2017 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"""Uploads RBE results to BigQuery"""
16
17import argparse
18import os
19import json
20import sys
21import urllib2
22import uuid
23
24gcp_utils_dir = os.path.abspath(
25    os.path.join(os.path.dirname(__file__), '../../gcp/utils'))
26sys.path.append(gcp_utils_dir)
27import big_query_utils
28
29_DATASET_ID = 'jenkins_test_results'
30_DESCRIPTION = 'Test results from master RBE builds on Kokoro'
31# 90 days in milliseconds
32_EXPIRATION_MS = 90 * 24 * 60 * 60 * 1000
33_PARTITION_TYPE = 'DAY'
34_PROJECT_ID = 'grpc-testing'
35_RESULTS_SCHEMA = [
36    ('job_name', 'STRING', 'Name of Kokoro job'),
37    ('build_id', 'INTEGER', 'Build ID of Kokoro job'),
38    ('build_url', 'STRING', 'URL of Kokoro build'),
39    ('test_target', 'STRING', 'Bazel target path'),
40    ('test_case', 'STRING', 'Name of test case'),
41    ('result', 'STRING', 'Test or build result'),
42    ('timestamp', 'TIMESTAMP', 'Timestamp of test run'),
43    ('duration', 'FLOAT', 'Duration of the test run'),
44]
45_TABLE_ID = 'rbe_test_results'
46
47
48def _get_api_key():
49    """Returns string with API key to access ResultStore.
50	Intended to be used in Kokoro environment."""
51    api_key_directory = os.getenv('KOKORO_GFILE_DIR')
52    api_key_file = os.path.join(api_key_directory, 'resultstore_api_key')
53    assert os.path.isfile(api_key_file), 'Must add --api_key arg if not on ' \
54     'Kokoro or Kokoro envrionment is not set up properly.'
55    with open(api_key_file, 'r') as f:
56        return f.read().replace('\n', '')
57
58
59def _get_invocation_id():
60    """Returns String of Bazel invocation ID. Intended to be used in
61	Kokoro environment."""
62    bazel_id_directory = os.getenv('KOKORO_ARTIFACTS_DIR')
63    bazel_id_file = os.path.join(bazel_id_directory, 'bazel_invocation_ids')
64    assert os.path.isfile(bazel_id_file), 'bazel_invocation_ids file, written ' \
65     'by bazel_wrapper.py, expected but not found.'
66    with open(bazel_id_file, 'r') as f:
67        return f.read().replace('\n', '')
68
69
70def _parse_test_duration(duration_str):
71    """Parse test duration string in '123.567s' format"""
72    try:
73        if duration_str.endswith('s'):
74            duration_str = duration_str[:-1]
75        return float(duration_str)
76    except:
77        return None
78
79
80def _upload_results_to_bq(rows):
81    """Upload test results to a BQ table.
82
83  Args:
84      rows: A list of dictionaries containing data for each row to insert
85  """
86    bq = big_query_utils.create_big_query()
87    big_query_utils.create_partitioned_table(
88        bq,
89        _PROJECT_ID,
90        _DATASET_ID,
91        _TABLE_ID,
92        _RESULTS_SCHEMA,
93        _DESCRIPTION,
94        partition_type=_PARTITION_TYPE,
95        expiration_ms=_EXPIRATION_MS)
96
97    max_retries = 3
98    for attempt in range(max_retries):
99        if big_query_utils.insert_rows(bq, _PROJECT_ID, _DATASET_ID, _TABLE_ID,
100                                       rows):
101            break
102        else:
103            if attempt < max_retries - 1:
104                print('Error uploading result to bigquery, will retry.')
105            else:
106                print(
107                    'Error uploading result to bigquery, all attempts failed.')
108                sys.exit(1)
109
110
111def _get_resultstore_data(api_key, invocation_id):
112    """Returns dictionary of test results by querying ResultStore API.
113  Args:
114      api_key: String of ResultStore API key
115      invocation_id: String of ResultStore invocation ID to results from
116  """
117    all_actions = []
118    page_token = ''
119    # ResultStore's API returns data on a limited number of tests. When we exceed
120    # that limit, the 'nextPageToken' field is included in the request to get
121    # subsequent data, so keep requesting until 'nextPageToken' field is omitted.
122    while True:
123        req = urllib2.Request(
124            url=
125            'https://resultstore.googleapis.com/v2/invocations/%s/targets/-/configuredTargets/-/actions?key=%s&pageToken=%s'
126            % (invocation_id, api_key, page_token),
127            headers={
128                'Content-Type': 'application/json'
129            })
130        results = json.loads(urllib2.urlopen(req).read())
131        all_actions.extend(results['actions'])
132        if 'nextPageToken' not in results:
133            break
134        page_token = results['nextPageToken']
135    return all_actions
136
137
138if __name__ == "__main__":
139    # Arguments are necessary if running in a non-Kokoro environment.
140    argp = argparse.ArgumentParser(description='Upload RBE results.')
141    argp.add_argument('--api_key', default='', type=str)
142    argp.add_argument('--invocation_id', default='', type=str)
143    args = argp.parse_args()
144
145    api_key = args.api_key or _get_api_key()
146    invocation_id = args.invocation_id or _get_invocation_id()
147    resultstore_actions = _get_resultstore_data(api_key, invocation_id)
148
149    bq_rows = []
150    for index, action in enumerate(resultstore_actions):
151        # Filter out non-test related data, such as build results.
152        if 'testAction' not in action:
153            continue
154        # Some test results contain the fileProcessingErrors field, which indicates
155        # an issue with parsing results individual test cases.
156        if 'fileProcessingErrors' in action:
157            test_cases = [{
158                'testCase': {
159                    'caseName': str(action['id']['actionId']),
160                }
161            }]
162        # Test timeouts have a different dictionary structure compared to pass and
163        # fail results.
164        elif action['statusAttributes']['status'] == 'TIMED_OUT':
165            test_cases = [{
166                'testCase': {
167                    'caseName': str(action['id']['actionId']),
168                    'timedOut': True
169                }
170            }]
171        # When RBE believes its infrastructure is failing, it will abort and
172        # mark running tests as UNKNOWN. These infrastructure failures may be
173        # related to our tests, so we should investigate if specific tests are
174        # repeatedly being marked as UNKNOWN.
175        elif action['statusAttributes']['status'] == 'UNKNOWN':
176            test_cases = [{
177                'testCase': {
178                    'caseName': str(action['id']['actionId']),
179                    'unknown': True
180                }
181            }]
182            # Take the timestamp from the previous action, which should be
183            # a close approximation.
184            action['timing'] = {
185                'startTime':
186                resultstore_actions[index - 1]['timing']['startTime']
187            }
188        else:
189            test_cases = action['testAction']['testSuite']['tests'][0][
190                'testSuite']['tests']
191        for test_case in test_cases:
192            if any(s in test_case['testCase'] for s in ['errors', 'failures']):
193                result = 'FAILED'
194            elif 'timedOut' in test_case['testCase']:
195                result = 'TIMEOUT'
196            elif 'unknown' in test_case['testCase']:
197                result = 'UNKNOWN'
198            else:
199                result = 'PASSED'
200            try:
201                bq_rows.append({
202                    'insertId': str(uuid.uuid4()),
203                    'json': {
204                        'job_name':
205                        os.getenv('KOKORO_JOB_NAME'),
206                        'build_id':
207                        os.getenv('KOKORO_BUILD_NUMBER'),
208                        'build_url':
209                        'https://source.cloud.google.com/results/invocations/%s'
210                        % invocation_id,
211                        'test_target':
212                        action['id']['targetId'],
213                        'test_case':
214                        test_case['testCase']['caseName'],
215                        'result':
216                        result,
217                        'timestamp':
218                        action['timing']['startTime'],
219                        'duration':
220                        _parse_test_duration(action['timing']['duration']),
221                    }
222                })
223            except Exception as e:
224                print('Failed to parse test result. Error: %s' % str(e))
225                print(json.dumps(test_case, indent=4))
226                bq_rows.append({
227                    'insertId': str(uuid.uuid4()),
228                    'json': {
229                        'job_name':
230                        os.getenv('KOKORO_JOB_NAME'),
231                        'build_id':
232                        os.getenv('KOKORO_BUILD_NUMBER'),
233                        'build_url':
234                        'https://source.cloud.google.com/results/invocations/%s'
235                        % invocation_id,
236                        'test_target':
237                        action['id']['targetId'],
238                        'test_case':
239                        'N/A',
240                        'result':
241                        'UNPARSEABLE',
242                        'timestamp':
243                        'N/A',
244                    }
245                })
246
247    # BigQuery sometimes fails with large uploads, so batch 1,000 rows at a time.
248    for i in range((len(bq_rows) / 1000) + 1):
249        _upload_results_to_bq(bq_rows[i * 1000:(i + 1) * 1000])
250