Debian Codegraph @

tools/codegen/core/gen_stats_data.py

raw
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 from __future__ import print_function
18
19 import collections
20 import ctypes
21 import json
22 import math
23 import sys
24
25 import yaml
26
27 with open('src/core/lib/debug/stats_data.yaml') as f:
28 attrs = yaml.load(f.read())
29
30 REQUIRED_FIELDS = ['name', 'doc']
31
32
33 def make_type(name, fields):
34 return (collections.namedtuple(
35 name, ' '.join(list(set(REQUIRED_FIELDS + fields)))), [])
36
37
38 def c_str(s, encoding='ascii'):
39 if isinstance(s, str):
40 s = s.encode(encoding)
41 result = ''
42 for c in s:
43 c = chr(c) if isinstance(c, int) else c
44 if not (32 <= ord(c) < 127) or c in ('\\', '"'):
45 result += '\\%03o' % ord(c)
46 else:
47 result += c
48 return '"' + result + '"'
49
50
51 types = (
52 make_type('Counter', []),
53 make_type('Histogram', ['max', 'buckets']),
54 )
55 Shape = collections.namedtuple('Shape', 'max buckets')
56
57 inst_map = dict((t[0].__name__, t[1]) for t in types)
58
59 stats = []
60
61 for attr in attrs:
62 found = False
63 for t, lst in types:
64 t_name = t.__name__.lower()
65 if t_name in attr:
66 name = attr[t_name]
67 del attr[t_name]
68 lst.append(t(name=name, **attr))
69 found = True
70 break
71 assert found, "Bad decl: %s" % attr
72
73
74 def dbl2u64(d):
75 return ctypes.c_ulonglong.from_buffer(ctypes.c_double(d)).value
76
77
78 def u642dbl(d):
79 return ctypes.c_double.from_buffer(ctypes.c_ulonglong(d)).value
80
81
82 def shift_works_until(mapped_bounds, shift_bits):
83 for i, ab in enumerate(zip(mapped_bounds, mapped_bounds[1:])):
84 a, b = ab
85 if (a >> shift_bits) == (b >> shift_bits):
86 return i
87 return len(mapped_bounds)
88
89
90 def find_ideal_shift(mapped_bounds, max_size):
91 best = None
92 for shift_bits in reversed(list(range(0, 64))):
93 n = shift_works_until(mapped_bounds, shift_bits)
94 if n == 0:
95 continue
96 table_size = mapped_bounds[n - 1] >> shift_bits
97 if table_size > max_size:
98 continue
99 if best is None:
100 best = (shift_bits, n, table_size)
101 elif best[1] < n:
102 best = (shift_bits, n, table_size)
103 return best
104
105
106 def gen_map_table(mapped_bounds, shift_data):
107 #print("gen_map_table(%s, %s)" % (mapped_bounds, shift_data))
108 tbl = []
109 cur = 0
110 mapped_bounds = [x >> shift_data[0] for x in mapped_bounds]
111 for i in range(0, mapped_bounds[shift_data[1] - 1]):
112 while i > mapped_bounds[cur]:
113 cur += 1
114 tbl.append(cur)
115 return tbl
116
117
118 static_tables = []
119
120
121 def decl_static_table(values, type):
122 global static_tables
123 v = (type, values)
124 for i, vp in enumerate(static_tables):
125 if v == vp:
126 return i
127 r = len(static_tables)
128 static_tables.append(v)
129 return r
130
131
132 def type_for_uint_table(table):
133 mv = max(table)
134 if mv < 2**8:
135 return 'uint8_t'
136 elif mv < 2**16:
137 return 'uint16_t'
138 elif mv < 2**32:
139 return 'uint32_t'
140 else:
141 return 'uint64_t'
142
143
144 def merge_cases(cases):
145 l = len(cases)
146 if l == 1:
147 return cases[0][1]
148 left_len = l // 2
149 left = cases[0:left_len]
150 right = cases[left_len:]
151 return 'if (value < %d) {\n%s\n} else {\n%s\n}' % (
152 left[-1][0], merge_cases(left), merge_cases(right))
153
154
155 def gen_bucket_code(shape):
156 bounds = [0, 1]
157 done_trivial = False
158 done_unmapped = False
159 first_nontrivial = None
160 first_unmapped = None
161 while len(bounds) < shape.buckets + 1:
162 if len(bounds) == shape.buckets:
163 nextb = int(shape.max)
164 else:
165 mul = math.pow(
166 float(shape.max) / bounds[-1],
167 1.0 / (shape.buckets + 1 - len(bounds)))
168 nextb = int(math.ceil(bounds[-1] * mul))
169 if nextb <= bounds[-1] + 1:
170 nextb = bounds[-1] + 1
171 elif not done_trivial:
172 done_trivial = True
173 first_nontrivial = len(bounds)
174 bounds.append(nextb)
175 bounds_idx = decl_static_table(bounds, 'int')
176 #print first_nontrivial, shift_data, bounds
177 #if shift_data is not None: print [hex(x >> shift_data[0]) for x in code_bounds[first_nontrivial:]]
178 if first_nontrivial is None:
179 return ('return grpc_core::Clamp(value, 0, %d);\n' % shape.max,
180 bounds_idx)
181 cases = [(0, 'return 0;'), (first_nontrivial, 'return value;')]
182 if done_trivial:
183 first_nontrivial_code = dbl2u64(first_nontrivial)
184 last_code = first_nontrivial_code
185 while True:
186 code = ''
187 first_nontrivial = u642dbl(first_nontrivial_code)
188 code_bounds_index = None
189 for i, b in enumerate(bounds):
190 if b > first_nontrivial:
191 code_bounds_index = i
192 break
193 code_bounds = [dbl2u64(x) - first_nontrivial_code for x in bounds]
194 shift_data = find_ideal_shift(code_bounds[code_bounds_index:],
195 65536)
196 if not shift_data:
197 break
198 map_table = gen_map_table(code_bounds[code_bounds_index:],
199 shift_data)
200 if not map_table:
201 break
202 if map_table[-1] < 5:
203 break
204 map_table_idx = decl_static_table(
205 [x + code_bounds_index for x in map_table],
206 type_for_uint_table(map_table))
207 last_code = (
208 (len(map_table) - 1) << shift_data[0]) + first_nontrivial_code
209 code += 'DblUint val;\n'
210 code += 'val.dbl = value;\n'
211 code += 'const int bucket = '
212 code += 'kStatsTable%d[((val.uint - %dull) >> %d)];\n' % (
213 map_table_idx, first_nontrivial_code, shift_data[0])
214 code += 'return bucket - (value < kStatsTable%d[bucket]);' % bounds_idx
215 cases.append((int(u642dbl(last_code)) + 1, code))
216 first_nontrivial_code = last_code
217 last = u642dbl(last_code) + 1
218 for i, b in enumerate(bounds[:-2]):
219 if bounds[i + 1] < last:
220 continue
221 cases.append((bounds[i + 1], 'return %d;' % i))
222 cases.append((None, 'return %d;' % (len(bounds) - 2)))
223 return (merge_cases(cases), bounds_idx)
224
225
226 # utility: print a big comment block into a set of files
227 def put_banner(files, banner):
228 for f in files:
229 print('/*', file=f)
230 for line in banner:
231 print(' * %s' % line, file=f)
232 print(' */', file=f)
233 print(file=f)
234
235
236 shapes = set()
237 for histogram in inst_map['Histogram']:
238 shapes.add(Shape(max=histogram.max, buckets=histogram.buckets))
239
240
241 def snake_to_pascal(name):
242 return ''.join([x.capitalize() for x in name.split('_')])
243
244
245 with open('src/core/lib/debug/stats_data.h', 'w') as H:
246 # copy-paste copyright notice from this file
247 with open(sys.argv[0]) as my_source:
248 copyright = []
249 for line in my_source:
250 if line[0] != '#':
251 break
252 for line in my_source:
253 if line[0] == '#':
254 copyright.append(line)
255 break
256 for line in my_source:
257 if line[0] != '#':
258 break
259 copyright.append(line)
260 put_banner([H], [line[2:].rstrip() for line in copyright])
261
262 put_banner(
263 [H],
264 ["Automatically generated by tools/codegen/core/gen_stats_data.py"])
265
266 print("#ifndef GRPC_CORE_LIB_DEBUG_STATS_DATA_H", file=H)
267 print("#define GRPC_CORE_LIB_DEBUG_STATS_DATA_H", file=H)
268 print(file=H)
269 print("#include <grpc/support/port_platform.h>", file=H)
270 print("#include <atomic>", file=H)
271 print("#include <memory>", file=H)
272 print("#include <stdint.h>", file=H)
273 print("#include \"src/core/lib/debug/histogram_view.h\"", file=H)
274 print("#include \"absl/strings/string_view.h\"", file=H)
275 print("#include \"src/core/lib/gprpp/per_cpu.h\"", file=H)
276 print(file=H)
277 print("namespace grpc_core {", file=H)
278
279 for shape in shapes:
280 print("class HistogramCollector_%d_%d;" % (shape.max, shape.buckets),
281 file=H)
282 print("class Histogram_%d_%d {" % (shape.max, shape.buckets), file=H)
283 print(" public:", file=H)
284 print(" static int BucketFor(int value);", file=H)
285 print(" const uint64_t* buckets() const { return buckets_; }", file=H)
286 print(
287 " friend Histogram_%d_%d operator-(const Histogram_%d_%d& left, const Histogram_%d_%d& right);"
288 % (shape.max, shape.buckets, shape.max, shape.buckets, shape.max,
289 shape.buckets),
290 file=H)
291 print(" private:", file=H)
292 print(" friend class HistogramCollector_%d_%d;" %
293 (shape.max, shape.buckets),
294 file=H)
295 print(" uint64_t buckets_[%d]{};" % shape.buckets, file=H)
296 print("};", file=H)
297 print("class HistogramCollector_%d_%d {" % (shape.max, shape.buckets),
298 file=H)
299 print(" public:", file=H)
300 print(" void Increment(int value) {", file=H)
301 print(" buckets_[Histogram_%d_%d::BucketFor(value)]" %
302 (shape.max, shape.buckets),
303 file=H)
304 print(" .fetch_add(1, std::memory_order_relaxed);", file=H)
305 print(" }", file=H)
306 print(" void Collect(Histogram_%d_%d* result) const;" %
307 (shape.max, shape.buckets),
308 file=H)
309 print(" private:", file=H)
310 print(" std::atomic<uint64_t> buckets_[%d]{};" % shape.buckets, file=H)
311 print("};", file=H)
312
313 print("struct GlobalStats {", file=H)
314 print(" enum class Counter {", file=H)
315 for ctr in inst_map['Counter']:
316 print(" k%s," % snake_to_pascal(ctr.name), file=H)
317 print(" COUNT", file=H)
318 print(" };", file=H)
319 print(" enum class Histogram {", file=H)
320 for ctr in inst_map['Histogram']:
321 print(" k%s," % snake_to_pascal(ctr.name), file=H)
322 print(" COUNT", file=H)
323 print(" };", file=H)
324 print(" GlobalStats();", file=H)
325 print(
326 " static const absl::string_view counter_name[static_cast<int>(Counter::COUNT)];",
327 file=H)
328 print(
329 " static const absl::string_view histogram_name[static_cast<int>(Histogram::COUNT)];",
330 file=H)
331 print(
332 " static const absl::string_view counter_doc[static_cast<int>(Counter::COUNT)];",
333 file=H)
334 print(
335 " static const absl::string_view histogram_doc[static_cast<int>(Histogram::COUNT)];",
336 file=H)
337 print(" union {", file=H)
338 print(" struct {", file=H)
339 for ctr in inst_map['Counter']:
340 print(" uint64_t %s;" % ctr.name, file=H)
341 print(" };", file=H)
342 print(" uint64_t counters[static_cast<int>(Counter::COUNT)];", file=H)
343 print(" };", file=H)
344 for ctr in inst_map['Histogram']:
345 print(" Histogram_%d_%d %s;" % (ctr.max, ctr.buckets, ctr.name),
346 file=H)
347 print(" HistogramView histogram(Histogram which) const;", file=H)
348 print(
349 " std::unique_ptr<GlobalStats> Diff(const GlobalStats& other) const;",
350 file=H)
351 print("};", file=H)
352 print("class GlobalStatsCollector {", file=H)
353 print(" public:", file=H)
354 print(" std::unique_ptr<GlobalStats> Collect() const;", file=H)
355 for ctr in inst_map['Counter']:
356 print(
357 " void Increment%s() { data_.this_cpu().%s.fetch_add(1, std::memory_order_relaxed); }"
358 % (snake_to_pascal(ctr.name), ctr.name),
359 file=H)
360 for ctr in inst_map['Histogram']:
361 print(
362 " void Increment%s(int value) { data_.this_cpu().%s.Increment(value); }"
363 % (snake_to_pascal(ctr.name), ctr.name),
364 file=H)
365 print(" private:", file=H)
366 print(" struct Data {", file=H)
367 for ctr in inst_map['Counter']:
368 print(" std::atomic<uint64_t> %s{0};" % ctr.name, file=H)
369 for ctr in inst_map['Histogram']:
370 print(" HistogramCollector_%d_%d %s;" %
371 (ctr.max, ctr.buckets, ctr.name),
372 file=H)
373 print(" };", file=H)
374 print(" PerCpu<Data> data_;", file=H)
375 print("};", file=H)
376 print("}", file=H)
377
378 print(file=H)
379 print("#endif /* GRPC_CORE_LIB_DEBUG_STATS_DATA_H */", file=H)
380
381 with open('src/core/lib/debug/stats_data.cc', 'w') as C:
382 # copy-paste copyright notice from this file
383 with open(sys.argv[0]) as my_source:
384 copyright = []
385 for line in my_source:
386 if line[0] != '#':
387 break
388 for line in my_source:
389 if line[0] == '#':
390 copyright.append(line)
391 break
392 for line in my_source:
393 if line[0] != '#':
394 break
395 copyright.append(line)
396 put_banner([C], [line[2:].rstrip() for line in copyright])
397
398 put_banner(
399 [C],
400 ["Automatically generated by tools/codegen/core/gen_stats_data.py"])
401
402 print("#include <grpc/support/port_platform.h>", file=C)
403 print(file=C)
404 print("#include \"src/core/lib/debug/stats_data.h\"", file=C)
405 print("#include <stdint.h>", file=C)
406 print("#include \"absl/memory/memory.h\"", file=C)
407 print(file=C)
408
409 histo_code = []
410 histo_bucket_boundaries = {}
411 for shape in shapes:
412 code, bounds_idx = gen_bucket_code(shape)
413 histo_bucket_boundaries[shape] = bounds_idx
414 histo_code.append(code)
415
416 print("namespace grpc_core {", file=C)
417 print("namespace { union DblUint { double dbl; uint64_t uint; }; }", file=C)
418
419 for shape in shapes:
420 print(
421 "void HistogramCollector_%d_%d::Collect(Histogram_%d_%d* result) const {"
422 % (shape.max, shape.buckets, shape.max, shape.buckets),
423 file=C)
424 print(" for (int i=0; i<%d; i++) {" % shape.buckets, file=C)
425 print(
426 " result->buckets_[i] += buckets_[i].load(std::memory_order_relaxed);",
427 file=C)
428 print(" }", file=C)
429 print("}", file=C)
430 print(
431 "Histogram_%d_%d operator-(const Histogram_%d_%d& left, const Histogram_%d_%d& right) {"
432 % (shape.max, shape.buckets, shape.max, shape.buckets, shape.max,
433 shape.buckets),
434 file=C)
435 print(" Histogram_%d_%d result;" % (shape.max, shape.buckets), file=C)
436 print(" for (int i=0; i<%d; i++) {" % shape.buckets, file=C)
437 print(" result.buckets_[i] = left.buckets_[i] - right.buckets_[i];",
438 file=C)
439 print(" }", file=C)
440 print(" return result;", file=C)
441 print("}", file=C)
442
443 for typename, instances in sorted(inst_map.items()):
444 print(
445 "const absl::string_view GlobalStats::%s_name[static_cast<int>(%s::COUNT)] = {"
446 % (typename.lower(), typename),
447 file=C)
448 for inst in instances:
449 print(" %s," % c_str(inst.name), file=C)
450 print("};", file=C)
451 print(
452 "const absl::string_view GlobalStats::%s_doc[static_cast<int>(%s::COUNT)] = {"
453 % (typename.lower(), typename),
454 file=C)
455 for inst in instances:
456 print(" %s," % c_str(inst.doc), file=C)
457 print("};", file=C)
458
459 print("namespace {", file=C)
460 for i, tbl in enumerate(static_tables):
461 print("const %s kStatsTable%d[%d] = {%s};" %
462 (tbl[0], i, len(tbl[1]), ','.join('%s' % x for x in tbl[1])),
463 file=C)
464 print("} // namespace", file=C)
465
466 for shape, code in zip(shapes, histo_code):
467 print(("int Histogram_%d_%d::BucketFor(int value) {%s}") %
468 (shape.max, shape.buckets, code),
469 file=C)
470
471 print("GlobalStats::GlobalStats() : %s {}" %
472 ",".join("%s{0}" % ctr.name for ctr in inst_map['Counter']),
473 file=C)
474
475 print("HistogramView GlobalStats::histogram(Histogram which) const {",
476 file=C)
477 print(" switch (which) {", file=C)
478 print(" default: GPR_UNREACHABLE_CODE(return HistogramView());", file=C)
479 for inst in inst_map['Histogram']:
480 print(" case Histogram::k%s:" % snake_to_pascal(inst.name), file=C)
481 print(
482 " return HistogramView{&Histogram_%d_%d::BucketFor, kStatsTable%d, %d, %s.buckets()};"
483 % (inst.max, inst.buckets, histo_bucket_boundaries[Shape(
484 inst.max, inst.buckets)], inst.buckets, inst.name),
485 file=C)
486 print(" }", file=C)
487 print("}", file=C)
488
489 print(
490 "std::unique_ptr<GlobalStats> GlobalStatsCollector::Collect() const {",
491 file=C)
492 print(" auto result = std::make_unique<GlobalStats>();", file=C)
493 print(" for (const auto& data : data_) {", file=C)
494 for ctr in inst_map['Counter']:
495 print(" result->%s += data.%s.load(std::memory_order_relaxed);" %
496 (ctr.name, ctr.name),
497 file=C)
498 for h in inst_map['Histogram']:
499 print(" data.%s.Collect(&result->%s);" % (h.name, h.name), file=C)
500 print(" }", file=C)
501 print(" return result;", file=C)
502 print("}", file=C)
503
504 print(
505 "std::unique_ptr<GlobalStats> GlobalStats::Diff(const GlobalStats& other) const {",
506 file=C)
507 print(" auto result = std::make_unique<GlobalStats>();", file=C)
508 for ctr in inst_map['Counter']:
509 print(" result->%s = %s - other.%s;" % (ctr.name, ctr.name, ctr.name),
510 file=C)
511 for h in inst_map['Histogram']:
512 print(" result->%s = %s - other.%s;" % (h.name, h.name, h.name),
513 file=C)
514 print(" return result;", file=C)
515 print("}", file=C)
516
517 print("}", file=C)