Debian Codegraph @

tools/codegen/core/gen_experiments.py

raw
1 #!/usr/bin/env python3
2
3 # Copyright 2022 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 Generate experiment related code artifacts.
18
19 Invoke as: tools/codegen/core/gen_experiments.py
20 Experiment definitions are in src/core/lib/experiments/experiments.yaml
21 """
22
23 from __future__ import print_function
24
25 import collections
26 import ctypes
27 import datetime
28 import json
29 import math
30 import os
31 import re
32 import sys
33
34 import yaml
35
36 # TODO(ctiller): if we ever add another argument switch this to argparse
37 check_dates = True
38 if sys.argv[1:] == ["--check"]:
39 check_dates = False # for formatting checks we don't verify expiry dates
40
41 with open('src/core/lib/experiments/experiments.yaml') as f:
42 attrs = yaml.load(f.read(), Loader=yaml.FullLoader)
43
44 DEFAULTS = {
45 'broken': 'false',
46 False: 'false',
47 True: 'true',
48 'debug': 'kDefaultForDebugOnly',
49 'release': 'kDefaultForReleaseOnly',
50 }
51
52 BZL_LIST_FOR_DEFAULTS = {
53 'broken': None,
54 False: 'off',
55 True: 'on',
56 'debug': 'dbg',
57 'release': 'opt',
58 }
59
60 error = False
61 today = datetime.date.today()
62 two_quarters_from_now = today + datetime.timedelta(days=180)
63 for attr in attrs:
64 if 'name' not in attr:
65 print("experiment with no name: %r" % attr)
66 error = True
67 continue # can't run other diagnostics because we don't know a name
68 if 'description' not in attr:
69 print("no description for experiment %s" % attr['name'])
70 error = True
71 if 'default' not in attr:
72 print("no default for experiment %s" % attr['name'])
73 error = True
74 if attr['default'] not in DEFAULTS:
75 print("invalid default for experiment %s: %r" %
76 (attr['name'], attr['default']))
77 error = True
78 if 'owner' not in attr:
79 print("no owner for experiment %s" % attr['name'])
80 error = True
81 if 'expiry' not in attr:
82 print("no expiry for experiment %s" % attr['name'])
83 error = True
84 expiry = datetime.datetime.strptime(attr['expiry'], '%Y/%m/%d').date()
85 if check_dates:
86 if expiry < today:
87 print("experiment %s expired on %s" %
88 (attr['name'], attr['expiry']))
89 error = True
90 if expiry > two_quarters_from_now:
91 print("experiment %s expires far in the future on %s" %
92 (attr['name'], attr['expiry']))
93 print("expiry should be no more than two quarters from now")
94 error = True
95
96 if error:
97 sys.exit(1)
98
99
100 def c_str(s, encoding='ascii'):
101 if isinstance(s, str):
102 s = s.encode(encoding)
103 result = ''
104 for c in s:
105 c = chr(c) if isinstance(c, int) else c
106 if not (32 <= ord(c) < 127) or c in ('\\', '"'):
107 result += '\\%03o' % ord(c)
108 else:
109 result += c
110 return '"' + result + '"'
111
112
113 def snake_to_pascal(s):
114 return ''.join(x.capitalize() for x in s.split('_'))
115
116
117 # utility: print a big comment block into a set of files
118 def put_banner(files, banner, prefix):
119 for f in files:
120 for line in banner:
121 if not line:
122 print(prefix, file=f)
123 else:
124 print('%s %s' % (prefix, line), file=f)
125 print(file=f)
126
127
128 def put_copyright(file, prefix):
129 # copy-paste copyright notice from this file
130 with open(sys.argv[0]) as my_source:
131 copyright = []
132 for line in my_source:
133 if line[0] != '#':
134 break
135 for line in my_source:
136 if line[0] == '#':
137 copyright.append(line)
138 break
139 for line in my_source:
140 if line[0] != '#':
141 break
142 copyright.append(line)
143 put_banner([file], [line[2:].rstrip() for line in copyright], prefix)
144
145
146 EXPERIMENT_METADATA = """struct ExperimentMetadata {
147 const char* name;
148 const char* description;
149 bool default_value;
150 };"""
151
152 with open('src/core/lib/experiments/experiments.h', 'w') as H:
153 put_copyright(H, "//")
154
155 put_banner(
156 [H],
157 ["Automatically generated by tools/codegen/core/gen_experiments.py"],
158 "//")
159
160 print("#ifndef GRPC_CORE_LIB_EXPERIMENTS_EXPERIMENTS_H", file=H)
161 print("#define GRPC_CORE_LIB_EXPERIMENTS_EXPERIMENTS_H", file=H)
162 print(file=H)
163 print("#include <grpc/support/port_platform.h>", file=H)
164 print(file=H)
165 print("#include <stddef.h>", file=H)
166 print("#include \"src/core/lib/experiments/config.h\"", file=H)
167 print(file=H)
168 print("namespace grpc_core {", file=H)
169 print(file=H)
170 for i, attr in enumerate(attrs):
171 print("inline bool Is%sEnabled() { return IsExperimentEnabled(%d); }" %
172 (snake_to_pascal(attr['name']), i),
173 file=H)
174 print(file=H)
175 print(EXPERIMENT_METADATA, file=H)
176 print(file=H)
177 print("constexpr const size_t kNumExperiments = %d;" % len(attrs), file=H)
178 print(
179 "extern const ExperimentMetadata g_experiment_metadata[kNumExperiments];",
180 file=H)
181 print(file=H)
182 print("} // namespace grpc_core", file=H)
183 print(file=H)
184 print("#endif // GRPC_CORE_LIB_EXPERIMENTS_EXPERIMENTS_H", file=H)
185
186 with open('src/core/lib/experiments/experiments.cc', 'w') as C:
187 put_copyright(C, "//")
188
189 put_banner(
190 [C],
191 ["Automatically generated by tools/codegen/core/gen_experiments.py"],
192 "//")
193
194 print("#include <grpc/support/port_platform.h>", file=C)
195 print("#include \"src/core/lib/experiments/experiments.h\"", file=C)
196 print(file=C)
197 print("namespace {", file=C)
198 for attr in attrs:
199 print("const char* const description_%s = %s;" %
200 (attr['name'], c_str(attr['description'])),
201 file=C)
202 have_defaults = set(DEFAULTS[attr['default']] for attr in attrs)
203 if 'kDefaultForDebugOnly' in have_defaults or 'kDefaultForReleaseOnly' in have_defaults:
204 print("#ifdef NDEBUG", file=C)
205 if 'kDefaultForDebugOnly' in have_defaults:
206 print("const bool kDefaultForDebugOnly = false;", file=C)
207 if 'kDefaultForReleaseOnly' in have_defaults:
208 print("const bool kDefaultForReleaseOnly = true;", file=C)
209 print("#else", file=C)
210 if 'kDefaultForDebugOnly' in have_defaults:
211 print("const bool kDefaultForDebugOnly = true;", file=C)
212 if 'kDefaultForReleaseOnly' in have_defaults:
213 print("const bool kDefaultForReleaseOnly = false;", file=C)
214 print("#endif", file=C)
215 print("}", file=C)
216 print(file=C)
217 print("namespace grpc_core {", file=C)
218 print(file=C)
219 print("const ExperimentMetadata g_experiment_metadata[] = {", file=C)
220 for attr in attrs:
221 print(" {%s, description_%s, %s}," %
222 (c_str(attr['name']), attr['name'], DEFAULTS[attr['default']]),
223 file=C)
224 print("};", file=C)
225 print(file=C)
226 print("} // namespace grpc_core", file=C)
227
228 bzl_to_tags_to_experiments = dict((key, collections.defaultdict(list))
229 for key in BZL_LIST_FOR_DEFAULTS.keys()
230 if key is not None)
231
232 for attr in attrs:
233 for tag in attr['test_tags']:
234 bzl_to_tags_to_experiments[attr['default']][tag].append(attr['name'])
235
236 with open('bazel/experiments.bzl', 'w') as B:
237 put_copyright(B, "#")
238
239 put_banner(
240 [B],
241 ["Automatically generated by tools/codegen/core/gen_experiments.py"],
242 "#")
243
244 print(
245 "\"\"\"Dictionary of tags to experiments so we know when to test different experiments.\"\"\"",
246 file=B)
247
248 bzl_to_tags_to_experiments = sorted(
249 (BZL_LIST_FOR_DEFAULTS[default], tags_to_experiments)
250 for default, tags_to_experiments in bzl_to_tags_to_experiments.items()
251 if BZL_LIST_FOR_DEFAULTS[default] is not None)
252
253 print(file=B)
254 print("EXPERIMENTS = {", file=B)
255 for key, tags_to_experiments in bzl_to_tags_to_experiments:
256 print(" \"%s\": {" % key, file=B)
257 for tag, experiments in sorted(tags_to_experiments.items()):
258 print(" \"%s\": [" % tag, file=B)
259 for experiment in sorted(experiments):
260 print(" \"%s\"," % experiment, file=B)
261 print(" ],", file=B)
262 print(" },", file=B)
263 print("}", file=B)