bq_upload_result.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python
  2. # Copyright 2016 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 performance benchmark result file to bigquery.
  16. from __future__ import print_function
  17. import argparse
  18. import calendar
  19. import json
  20. import os
  21. import sys
  22. import time
  23. import uuid
  24. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  25. import massage_qps_stats
  26. gcp_utils_dir = os.path.abspath(
  27. os.path.join(os.path.dirname(__file__), '../../gcp/utils'))
  28. sys.path.append(gcp_utils_dir)
  29. import big_query_utils
  30. _PROJECT_ID = 'grpc-testing'
  31. def _upload_netperf_latency_csv_to_bigquery(dataset_id, table_id, result_file):
  32. with open(result_file, 'r') as f:
  33. (col1, col2, col3) = f.read().split(',')
  34. latency50 = float(col1.strip()) * 1000
  35. latency90 = float(col2.strip()) * 1000
  36. latency99 = float(col3.strip()) * 1000
  37. scenario_result = {
  38. 'scenario': {
  39. 'name': 'netperf_tcp_rr'
  40. },
  41. 'summary': {
  42. 'latency50': latency50,
  43. 'latency90': latency90,
  44. 'latency99': latency99
  45. }
  46. }
  47. bq = big_query_utils.create_big_query()
  48. _create_results_table(bq, dataset_id, table_id)
  49. if not _insert_result(
  50. bq, dataset_id, table_id, scenario_result, flatten=False):
  51. print('Error uploading result to bigquery.')
  52. sys.exit(1)
  53. def _upload_scenario_result_to_bigquery(dataset_id, table_id, result_file,
  54. metadata_file, node_info_file):
  55. with open(result_file, 'r') as f:
  56. scenario_result = json.loads(f.read())
  57. bq = big_query_utils.create_big_query()
  58. _create_results_table(bq, dataset_id, table_id)
  59. if not _insert_scenario_result(bq, dataset_id, table_id, scenario_result,
  60. metadata_file, node_info_file):
  61. print('Error uploading result to bigquery.')
  62. sys.exit(1)
  63. def _insert_result(bq, dataset_id, table_id, scenario_result, flatten=True):
  64. if flatten:
  65. _flatten_result_inplace(scenario_result)
  66. _populate_metadata_inplace(scenario_result)
  67. row = big_query_utils.make_row(str(uuid.uuid4()), scenario_result)
  68. return big_query_utils.insert_rows(bq, _PROJECT_ID, dataset_id, table_id,
  69. [row])
  70. def _insert_scenario_result(bq,
  71. dataset_id,
  72. table_id,
  73. scenario_result,
  74. test_metadata_file,
  75. node_info_file,
  76. flatten=True):
  77. if flatten:
  78. _flatten_result_inplace(scenario_result)
  79. _populate_metadata_from_file(scenario_result, test_metadata_file)
  80. _populate_node_metadata_from_file(scenario_result, node_info_file)
  81. row = big_query_utils.make_row(str(uuid.uuid4()), scenario_result)
  82. return big_query_utils.insert_rows(bq, _PROJECT_ID, dataset_id, table_id,
  83. [row])
  84. def _create_results_table(bq, dataset_id, table_id):
  85. with open(os.path.dirname(__file__) + '/scenario_result_schema.json',
  86. 'r') as f:
  87. table_schema = json.loads(f.read())
  88. desc = 'Results of performance benchmarks.'
  89. return big_query_utils.create_table2(bq, _PROJECT_ID, dataset_id, table_id,
  90. table_schema, desc)
  91. def _flatten_result_inplace(scenario_result):
  92. """Bigquery is not really great for handling deeply nested data
  93. and repeated fields. To maintain values of some fields while keeping
  94. the schema relatively simple, we artificially leave some of the fields
  95. as JSON strings.
  96. """
  97. scenario_result['scenario']['clientConfig'] = json.dumps(
  98. scenario_result['scenario']['clientConfig'])
  99. scenario_result['scenario']['serverConfig'] = json.dumps(
  100. scenario_result['scenario']['serverConfig'])
  101. scenario_result['latencies'] = json.dumps(scenario_result['latencies'])
  102. scenario_result['serverCpuStats'] = []
  103. for stats in scenario_result['serverStats']:
  104. scenario_result['serverCpuStats'].append(dict())
  105. scenario_result['serverCpuStats'][-1]['totalCpuTime'] = stats.pop(
  106. 'totalCpuTime', None)
  107. scenario_result['serverCpuStats'][-1]['idleCpuTime'] = stats.pop(
  108. 'idleCpuTime', None)
  109. for stats in scenario_result['clientStats']:
  110. stats['latencies'] = json.dumps(stats['latencies'])
  111. stats.pop('requestResults', None)
  112. scenario_result['serverCores'] = json.dumps(scenario_result['serverCores'])
  113. scenario_result['clientSuccess'] = json.dumps(
  114. scenario_result['clientSuccess'])
  115. scenario_result['serverSuccess'] = json.dumps(
  116. scenario_result['serverSuccess'])
  117. scenario_result['requestResults'] = json.dumps(
  118. scenario_result.get('requestResults', []))
  119. scenario_result['serverCpuUsage'] = scenario_result['summary'].pop(
  120. 'serverCpuUsage', None)
  121. scenario_result['summary'].pop('successfulRequestsPerSecond', None)
  122. scenario_result['summary'].pop('failedRequestsPerSecond', None)
  123. massage_qps_stats.massage_qps_stats(scenario_result)
  124. def _populate_metadata_inplace(scenario_result):
  125. """Populates metadata based on environment variables set by Jenkins."""
  126. # NOTE: Grabbing the Kokoro environment variables will only work if the
  127. # driver is running locally on the same machine where Kokoro has started
  128. # the job. For our setup, this is currently the case, so just assume that.
  129. build_number = os.getenv('KOKORO_BUILD_NUMBER')
  130. build_url = 'https://source.cloud.google.com/results/invocations/%s' % os.getenv(
  131. 'KOKORO_BUILD_ID')
  132. job_name = os.getenv('KOKORO_JOB_NAME')
  133. git_commit = os.getenv('KOKORO_GIT_COMMIT')
  134. # actual commit is the actual head of PR that is getting tested
  135. # TODO(jtattermusch): unclear how to obtain on Kokoro
  136. git_actual_commit = os.getenv('ghprbActualCommit')
  137. utc_timestamp = str(calendar.timegm(time.gmtime()))
  138. metadata = {'created': utc_timestamp}
  139. if build_number:
  140. metadata['buildNumber'] = build_number
  141. if build_url:
  142. metadata['buildUrl'] = build_url
  143. if job_name:
  144. metadata['jobName'] = job_name
  145. if git_commit:
  146. metadata['gitCommit'] = git_commit
  147. if git_actual_commit:
  148. metadata['gitActualCommit'] = git_actual_commit
  149. scenario_result['metadata'] = metadata
  150. def _populate_metadata_from_file(scenario_result, test_metadata_file):
  151. utc_timestamp = str(calendar.timegm(time.gmtime()))
  152. metadata = {'created': utc_timestamp}
  153. _annotation_to_bq_metadata_key_map = {
  154. 'ci_' + key: key for key in (
  155. 'buildNumber',
  156. 'buildUrl',
  157. 'jobName',
  158. 'gitCommit',
  159. 'gitActualCommit',
  160. )
  161. }
  162. if os.access(test_metadata_file, os.R_OK):
  163. with open(test_metadata_file, 'r') as f:
  164. test_metadata = json.loads(f.read())
  165. # eliminate managedFields from metadata set
  166. if 'managedFields' in test_metadata:
  167. del test_metadata['managedFields']
  168. annotations = test_metadata.get('annotations', {})
  169. # if use kubectl apply ..., kubectl will append current configuration to
  170. # annotation, the field is deleted since it includes a lot of irrelevant
  171. # information
  172. if 'kubectl.kubernetes.io/last-applied-configuration' in annotations:
  173. del annotations['kubectl.kubernetes.io/last-applied-configuration']
  174. # dump all metadata as JSON to testMetadata field
  175. scenario_result['testMetadata'] = json.dumps(test_metadata)
  176. for key, value in _annotation_to_bq_metadata_key_map.items():
  177. if key in annotations:
  178. metadata[value] = annotations[key]
  179. scenario_result['metadata'] = metadata
  180. def _populate_node_metadata_from_file(scenario_result, node_info_file):
  181. node_metadata = {'driver': {}, 'servers': [], 'clients': []}
  182. _node_info_to_bq_node_metadata_key_map = {
  183. 'Name': 'name',
  184. 'PodIP': 'podIP',
  185. 'NodeName': 'nodeName',
  186. }
  187. if os.access(node_info_file, os.R_OK):
  188. with open(node_info_file, 'r') as f:
  189. file_metadata = json.loads(f.read())
  190. for key, value in _node_info_to_bq_node_metadata_key_map.items():
  191. node_metadata['driver'][value] = file_metadata['Driver'][key]
  192. for clientNodeInfo in file_metadata['Clients']:
  193. node_metadata['clients'].append({
  194. value: clientNodeInfo[key] for key, value in
  195. _node_info_to_bq_node_metadata_key_map.items()
  196. })
  197. for serverNodeInfo in file_metadata['Servers']:
  198. node_metadata['servers'].append({
  199. value: serverNodeInfo[key] for key, value in
  200. _node_info_to_bq_node_metadata_key_map.items()
  201. })
  202. scenario_result['nodeMetadata'] = node_metadata
  203. argp = argparse.ArgumentParser(description='Upload result to big query.')
  204. argp.add_argument('--bq_result_table',
  205. required=True,
  206. default=None,
  207. type=str,
  208. help='Bigquery "dataset.table" to upload results to.')
  209. argp.add_argument('--file_to_upload',
  210. default='scenario_result.json',
  211. type=str,
  212. help='Report file to upload.')
  213. argp.add_argument('--metadata_file_to_upload',
  214. default='metadata.json',
  215. type=str,
  216. help='Metadata file to upload.')
  217. argp.add_argument('--node_info_file_to_upload',
  218. default='node_info.json',
  219. type=str,
  220. help='Node information file to upload.')
  221. argp.add_argument('--file_format',
  222. choices=['scenario_result', 'netperf_latency_csv'],
  223. default='scenario_result',
  224. help='Format of the file to upload.')
  225. args = argp.parse_args()
  226. dataset_id, table_id = args.bq_result_table.split('.', 2)
  227. if args.file_format == 'netperf_latency_csv':
  228. _upload_netperf_latency_csv_to_bigquery(dataset_id, table_id,
  229. args.file_to_upload)
  230. else:
  231. _upload_scenario_result_to_bigquery(dataset_id, table_id,
  232. args.file_to_upload,
  233. args.metadata_file_to_upload,
  234. args.node_info_file_to_upload)
  235. print('Successfully uploaded %s, %s and %s to BigQuery.\n' %
  236. (args.file_to_upload, args.metadata_file_to_upload,
  237. args.node_info_file_to_upload))