xref: /aosp_15_r20/external/grpc-grpc/tools/profiling/microbenchmarks/bm2bq.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env python3
2#
3# Copyright 2017 gRPC authors.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Convert google-benchmark json output to something that can be uploaded to
18# BigQuery
19
20import csv
21import json
22import subprocess
23import sys
24
25import bm_json
26
27columns = []
28
29for row in json.loads(
30    # TODO(jtattermusch): make sure the dataset name is not hardcoded
31    subprocess.check_output(
32        ["bq", "--format=json", "show", "microbenchmarks.microbenchmarks"]
33    )
34)["schema"]["fields"]:
35    columns.append((row["name"], row["type"].lower()))
36
37SANITIZE = {
38    "integer": int,
39    "float": float,
40    "boolean": bool,
41    "string": str,
42    "timestamp": str,
43}
44
45# TODO(jtattermusch): add proper argparse argument, rather than trying
46# to emulate with manual argv inspection.
47if sys.argv[1] == "--schema":
48    print(",\n".join("%s:%s" % (k, t.upper()) for k, t in columns))
49    sys.exit(0)
50
51with open(sys.argv[1]) as f:
52    js = json.loads(f.read())
53
54if len(sys.argv) > 2:
55    with open(sys.argv[2]) as f:
56        js2 = json.loads(f.read())
57else:
58    js2 = None
59
60# TODO(jtattermusch): write directly to a file instead of stdout
61writer = csv.DictWriter(sys.stdout, [c for c, t in columns])
62
63for row in bm_json.expand_json(js, js2):
64    sane_row = {}
65    for name, sql_type in columns:
66        if name in row:
67            if row[name] == "":
68                continue
69            sane_row[name] = SANITIZE[sql_type](row[name])
70    writer.writerow(sane_row)
71