Debian Codegraph @

tools/distrib/fix_build_deps.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 import argparse
18 import collections
19 from doctest import SKIP
20 import multiprocessing
21 import os
22 import re
23 import sys
24
25 import run_buildozer
26
27 # find our home
28 ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
29 os.chdir(ROOT)
30
31 vendors = collections.defaultdict(list)
32 scores = collections.defaultdict(int)
33 avoidness = collections.defaultdict(int)
34 consumes = {}
35 no_update = set()
36 buildozer_commands = []
37 needs_codegen_base_src = set()
38 original_deps = {}
39 original_external_deps = {}
40 skip_headers = collections.defaultdict(set)
41
42 # TODO(ctiller): ideally we wouldn't hardcode a bunch of paths here.
43 # We can likely parse out BUILD files from dependencies to generate this index.
44 EXTERNAL_DEPS = {
45 'absl/algorithm/container.h':
46 'absl/algorithm:container',
47 'absl/base/attributes.h':
48 'absl/base:core_headers',
49 'absl/base/call_once.h':
50 'absl/base',
51 # TODO(ctiller) remove this
52 'absl/base/internal/endian.h':
53 'absl/base',
54 'absl/base/thread_annotations.h':
55 'absl/base:core_headers',
56 'absl/container/flat_hash_map.h':
57 'absl/container:flat_hash_map',
58 'absl/container/flat_hash_set.h':
59 'absl/container:flat_hash_set',
60 'absl/container/inlined_vector.h':
61 'absl/container:inlined_vector',
62 'absl/cleanup/cleanup.h':
63 'absl/cleanup',
64 'absl/debugging/failure_signal_handler.h':
65 'absl/debugging:failure_signal_handler',
66 'absl/debugging/stacktrace.h':
67 'absl/debugging:stacktrace',
68 'absl/debugging/symbolize.h':
69 'absl/debugging:symbolize',
70 'absl/flags/flag.h':
71 'absl/flags:flag',
72 'absl/flags/parse.h':
73 'absl/flags:parse',
74 'absl/functional/any_invocable.h':
75 'absl/functional:any_invocable',
76 'absl/functional/bind_front.h':
77 'absl/functional:bind_front',
78 'absl/functional/function_ref.h':
79 'absl/functional:function_ref',
80 'absl/hash/hash.h':
81 'absl/hash',
82 'absl/memory/memory.h':
83 'absl/memory',
84 'absl/meta/type_traits.h':
85 'absl/meta:type_traits',
86 'absl/random/random.h':
87 'absl/random',
88 'absl/random/distributions.h':
89 'absl/random:distributions',
90 'absl/status/status.h':
91 'absl/status',
92 'absl/status/statusor.h':
93 'absl/status:statusor',
94 'absl/strings/ascii.h':
95 'absl/strings',
96 'absl/strings/cord.h':
97 'absl/strings:cord',
98 'absl/strings/escaping.h':
99 'absl/strings',
100 'absl/strings/match.h':
101 'absl/strings',
102 'absl/strings/numbers.h':
103 'absl/strings',
104 'absl/strings/str_cat.h':
105 'absl/strings',
106 'absl/strings/str_format.h':
107 'absl/strings:str_format',
108 'absl/strings/str_join.h':
109 'absl/strings',
110 'absl/strings/str_replace.h':
111 'absl/strings',
112 'absl/strings/str_split.h':
113 'absl/strings',
114 'absl/strings/string_view.h':
115 'absl/strings',
116 'absl/strings/strip.h':
117 'absl/strings',
118 'absl/strings/substitute.h':
119 'absl/strings',
120 'absl/synchronization/mutex.h':
121 'absl/synchronization',
122 'absl/synchronization/notification.h':
123 'absl/synchronization',
124 'absl/time/clock.h':
125 'absl/time',
126 'absl/time/time.h':
127 'absl/time',
128 'absl/types/optional.h':
129 'absl/types:optional',
130 'absl/types/span.h':
131 'absl/types:span',
132 'absl/types/variant.h':
133 'absl/types:variant',
134 'absl/utility/utility.h':
135 'absl/utility',
136 'address_sorting/address_sorting.h':
137 'address_sorting',
138 'ares.h':
139 'cares',
140 'gmock/gmock.h':
141 'gtest',
142 'gtest/gtest.h':
143 'gtest',
144 'opencensus/trace/context_util.h':
145 'opencensus-trace-context_util',
146 'opencensus/trace/propagation/grpc_trace_bin.h':
147 'opencensus-trace-propagation',
148 'opencensus/tags/context_util.h':
149 'opencensus-tags-context_util',
150 'openssl/base.h':
151 'libssl',
152 'openssl/bio.h':
153 'libssl',
154 'openssl/bn.h':
155 'libcrypto',
156 'openssl/buffer.h':
157 'libcrypto',
158 'openssl/crypto.h':
159 'libcrypto',
160 'openssl/digest.h':
161 'libssl',
162 'openssl/engine.h':
163 'libcrypto',
164 'openssl/err.h':
165 'libcrypto',
166 'openssl/evp.h':
167 'libcrypto',
168 'openssl/hmac.h':
169 'libcrypto',
170 'openssl/pem.h':
171 'libcrypto',
172 'openssl/rsa.h':
173 'libcrypto',
174 'openssl/sha.h':
175 'libcrypto',
176 'openssl/ssl.h':
177 'libssl',
178 'openssl/tls1.h':
179 'libssl',
180 'openssl/x509.h':
181 'libcrypto',
182 'openssl/x509v3.h':
183 'libcrypto',
184 're2/re2.h':
185 're2',
186 'upb/arena.h':
187 'upb_lib',
188 'upb/def.h':
189 'upb_lib',
190 'upb/json_encode.h':
191 'upb_json_lib',
192 'upb/text_encode.h':
193 'upb_textformat_lib',
194 'upb/def.hpp':
195 'upb_reflection',
196 'upb/upb.h':
197 'upb_lib',
198 'upb/upb.hpp':
199 'upb_lib',
200 'xxhash.h':
201 'xxhash',
202 'zlib.h':
203 'madler_zlib',
204 }
205
206 INTERNAL_DEPS = {
207 'google/api/expr/v1alpha1/syntax.upb.h':
208 'google_type_expr_upb',
209 'google/rpc/status.upb.h':
210 'google_rpc_status_upb',
211 'google/protobuf/any.upb.h':
212 'protobuf_any_upb',
213 'google/protobuf/duration.upb.h':
214 'protobuf_duration_upb',
215 'google/protobuf/struct.upb.h':
216 'protobuf_struct_upb',
217 'google/protobuf/timestamp.upb.h':
218 'protobuf_timestamp_upb',
219 'google/protobuf/wrappers.upb.h':
220 'protobuf_wrappers_upb',
221 'grpc/status.h':
222 'grpc_public_hdrs',
223 'src/proto/grpc/channelz/channelz.grpc.pb.h':
224 '//src/proto/grpc/channelz:channelz_proto',
225 'src/proto/grpc/core/stats.pb.h':
226 '//src/proto/grpc/core:stats_proto',
227 'src/proto/grpc/health/v1/health.upb.h':
228 'grpc_health_upb',
229 'src/proto/grpc/lb/v1/load_reporter.grpc.pb.h':
230 '//src/proto/grpc/lb/v1:load_reporter_proto',
231 'src/proto/grpc/lb/v1/load_balancer.upb.h':
232 'grpc_lb_upb',
233 'src/proto/grpc/reflection/v1alpha/reflection.grpc.pb.h':
234 '//src/proto/grpc/reflection/v1alpha:reflection_proto',
235 'src/proto/grpc/gcp/transport_security_common.upb.h':
236 'alts_upb',
237 'src/proto/grpc/gcp/altscontext.upb.h':
238 'alts_upb',
239 'src/proto/grpc/lookup/v1/rls.upb.h':
240 'rls_upb',
241 'src/proto/grpc/lookup/v1/rls_config.upb.h':
242 'rls_config_upb',
243 'src/proto/grpc/lookup/v1/rls_config.upbdefs.h':
244 'rls_config_upbdefs',
245 'src/proto/grpc/testing/xds/v3/csds.grpc.pb.h':
246 '//src/proto/grpc/testing/xds/v3:csds_proto',
247 'xds/data/orca/v3/orca_load_report.upb.h':
248 'xds_orca_upb',
249 'xds/service/orca/v3/orca.upb.h':
250 'xds_orca_service_upb',
251 'xds/type/v3/typed_struct.upb.h':
252 'xds_type_upb',
253 }
254
255
256 class FakeSelects:
257
258 def config_setting_group(self, **kwargs):
259 pass
260
261
262 num_cc_libraries = 0
263 num_opted_out_cc_libraries = 0
264 parsing_path = None
265
266
267 # Convert the source or header target to a relative path.
268 def _get_filename(name, parsing_path):
269 filename = '%s%s' % (
270 (parsing_path + '/' if
271 (parsing_path and not name.startswith('//')) else ''), name)
272 filename = filename.replace('//:', '')
273 return filename.replace('//src/core:', 'src/core/')
274
275
276 def grpc_cc_library(name,
277 hdrs=[],
278 public_hdrs=[],
279 srcs=[],
280 select_deps=None,
281 tags=[],
282 deps=[],
283 external_deps=[],
284 proto=None,
285 **kwargs):
286 global args
287 global num_cc_libraries
288 global num_opted_out_cc_libraries
289 global parsing_path
290 assert (parsing_path is not None)
291 name = '//%s:%s' % (parsing_path, name)
292 num_cc_libraries += 1
293 if select_deps or 'nofixdeps' in tags:
294 if args.whats_left and not select_deps and 'nofixdeps' not in tags:
295 num_opted_out_cc_libraries += 1
296 print("Not opted in: {}".format(name))
297 no_update.add(name)
298 scores[name] = len(public_hdrs + hdrs)
299 # avoid_dep is the internal way of saying prefer something else
300 # we add grpc_avoid_dep to allow internal grpc-only stuff to avoid each
301 # other, whilst not biasing dependent projects
302 if 'avoid_dep' in tags or 'grpc_avoid_dep' in tags:
303 avoidness[name] += 10
304 if proto:
305 proto_hdr = '%s%s' % ((parsing_path + '/' if parsing_path else ''),
306 proto.replace('.proto', '.pb.h'))
307 skip_headers[name].add(proto_hdr)
308
309 for hdr in hdrs + public_hdrs:
310 vendors[_get_filename(hdr, parsing_path)].append(name)
311 inc = set()
312 original_deps[name] = frozenset(deps)
313 original_external_deps[name] = frozenset(external_deps)
314 for src in hdrs + public_hdrs + srcs:
315 for line in open(_get_filename(src, parsing_path)):
316 m = re.search(r'^#include <(.*)>', line)
317 if m:
318 inc.add(m.group(1))
319 m = re.search(r'^#include "(.*)"', line)
320 if m:
321 inc.add(m.group(1))
322 if 'grpc::g_glip' in line or 'grpc::g_core_codegen_interface' in line:
323 needs_codegen_base_src.add(name)
324 consumes[name] = list(inc)
325
326
327 def buildozer(cmd, target):
328 buildozer_commands.append('%s|%s' % (cmd, target))
329
330
331 def buildozer_set_list(name, values, target, via=""):
332 if not values:
333 buildozer('remove %s' % name, target)
334 return
335 adjust = via if via else name
336 buildozer('set %s %s' % (adjust, ' '.join('"%s"' % s for s in values)),
337 target)
338 if via:
339 buildozer('remove %s' % name, target)
340 buildozer('rename %s %s' % (via, name), target)
341
342
343 def score_edit_distance(proposed, existing):
344 """Score a proposed change primarily by edit distance"""
345 sum = 0
346 for p in proposed:
347 if p not in existing:
348 sum += 1
349 for e in existing:
350 if e not in proposed:
351 sum += 1
352 return sum
353
354
355 def total_score(proposal):
356 return sum(scores[dep] for dep in proposal)
357
358
359 def total_avoidness(proposal):
360 return sum(avoidness[dep] for dep in proposal)
361
362
363 def score_list_size(proposed, existing):
364 """Score a proposed change primarily by number of dependencies"""
365 return len(proposed)
366
367
368 def score_best(proposed, existing):
369 """Score a proposed change primarily by dependency score"""
370 return 0
371
372
373 SCORERS = {
374 'edit_distance': score_edit_distance,
375 'list_size': score_list_size,
376 'best': score_best,
377 }
378
379 parser = argparse.ArgumentParser(description='Fix build dependencies')
380 parser.add_argument('targets',
381 nargs='*',
382 default=[],
383 help='targets to fix (empty => all)')
384 parser.add_argument('--score',
385 type=str,
386 default='edit_distance',
387 help='scoring function to use: one of ' +
388 ', '.join(SCORERS.keys()))
389 parser.add_argument('--whats_left',
390 action='store_true',
391 default=False,
392 help='show what is left to opt in')
393 parser.add_argument('--explain',
394 action='store_true',
395 default=False,
396 help='try to explain some decisions')
397 parser.add_argument(
398 '--why',
399 type=str,
400 default=None,
401 help='with --explain, target why a given dependency is needed')
402 args = parser.parse_args()
403
404 for dirname in [
405 "",
406 "src/core",
407 "src/cpp/ext/gcp",
408 "test/core/uri",
409 "test/core/util",
410 "test/core/end2end",
411 "test/core/event_engine",
412 "test/core/resource_quota",
413 ]:
414 parsing_path = dirname
415 exec(
416 open('%sBUILD' % (dirname + '/' if dirname else ''), 'r').read(), {
417 'load': lambda filename, *args: None,
418 'licenses': lambda licenses: None,
419 'package': lambda **kwargs: None,
420 'exports_files': lambda files, visibility=None: None,
421 'config_setting': lambda **kwargs: None,
422 'selects': FakeSelects(),
423 'python_config_settings': lambda **kwargs: None,
424 'grpc_cc_binary': grpc_cc_library,
425 'grpc_cc_library': grpc_cc_library,
426 'grpc_cc_test': grpc_cc_library,
427 'grpc_fuzzer': grpc_cc_library,
428 'grpc_proto_fuzzer': grpc_cc_library,
429 'select': lambda d: d["//conditions:default"],
430 'glob': lambda files: None,
431 'grpc_end2end_tests': lambda: None,
432 'grpc_upb_proto_library': lambda name, **kwargs: None,
433 'grpc_upb_proto_reflection_library': lambda name, **kwargs: None,
434 'grpc_generate_one_off_targets': lambda: None,
435 'grpc_package': lambda **kwargs: None,
436 'filegroup': lambda name, **kwargs: None,
437 'sh_library': lambda name, **kwargs: None,
438 }, {})
439 parsing_path = None
440
441 if args.whats_left:
442 print("{}/{} libraries are opted in".format(
443 num_cc_libraries - num_opted_out_cc_libraries, num_cc_libraries))
444
445
446 def make_relative_path(dep, lib):
447 if lib is None:
448 return dep
449 lib_path = lib[:lib.rfind(':') + 1]
450 if dep.startswith(lib_path):
451 return dep[len(lib_path):]
452 return dep
453
454
455 if args.whats_left:
456 print("{}/{} libraries are opted in".format(
457 num_cc_libraries - num_opted_out_cc_libraries, num_cc_libraries))
458
459
460 # Keeps track of all possible sets of dependencies that could satify the
461 # problem. (models the list monad in Haskell!)
462 class Choices:
463
464 def __init__(self, library, substitutions):
465 self.library = library
466 self.to_add = []
467 self.to_remove = []
468 self.substitutions = substitutions
469
470 def add_one_of(self, choices, trigger):
471 if not choices:
472 return
473 choices = sum([self.apply_substitutions(choice) for choice in choices],
474 [])
475 if args.explain and (args.why is None or args.why in choices):
476 print("{}: Adding one of {} for {}".format(self.library, choices,
477 trigger))
478 self.to_add.append(
479 tuple(
480 make_relative_path(choice, self.library) for choice in choices))
481
482 def add(self, choice, trigger):
483 self.add_one_of([choice], trigger)
484
485 def remove(self, remove):
486 for remove in self.apply_substitutions(remove):
487 self.to_remove.append(make_relative_path(remove, self.library))
488
489 def apply_substitutions(self, dep):
490 if dep in self.substitutions:
491 return self.substitutions[dep]
492 return [dep]
493
494 def best(self, scorer):
495 choices = set()
496 choices.add(frozenset())
497
498 for add in sorted(set(self.to_add), key=lambda x: (len(x), x)):
499 new_choices = set()
500 for append_choice in add:
501 for choice in choices:
502 new_choices.add(choice.union([append_choice]))
503 choices = new_choices
504 for remove in sorted(set(self.to_remove)):
505 new_choices = set()
506 for choice in choices:
507 new_choices.add(choice.difference([remove]))
508 choices = new_choices
509
510 best = None
511
512 def final_scorer(x):
513 return (total_avoidness(x), scorer(x), total_score(x))
514
515 for choice in choices:
516 if best is None or final_scorer(choice) < final_scorer(best):
517 best = choice
518 return best
519
520
521 def make_library(library):
522 error = False
523 hdrs = sorted(consumes[library])
524 # we need a little trickery here since grpc_base has channel.cc, which calls grpc_init
525 # which is in grpc, which is illegal but hard to change
526 # once event engine lands we can clean this up
527 deps = Choices(library, {'//:grpc_base': ['//:grpc', '//:grpc_unsecure']}
528 if library.startswith('//test/') else {})
529 external_deps = Choices(None, {})
530 for hdr in hdrs:
531 if hdr in skip_headers[library]:
532 continue
533
534 if hdr == 'src/core/lib/profiling/stap_probes.h':
535 continue
536
537 if hdr.startswith('src/libfuzzer/'):
538 continue
539
540 if hdr == 'grpc/grpc.h' and library.startswith('//test:'):
541 # not the root build including grpc.h ==> //:grpc
542 deps.add_one_of(['//:grpc', '//:grpc_unsecure'], hdr)
543 continue
544
545 if hdr in INTERNAL_DEPS:
546 dep = INTERNAL_DEPS[hdr]
547 if not dep.startswith('//'):
548 dep = '//:' + dep
549 deps.add(dep, hdr)
550 continue
551
552 if hdr in vendors:
553 deps.add_one_of(vendors[hdr], hdr)
554 continue
555
556 if 'include/' + hdr in vendors:
557 deps.add_one_of(vendors['include/' + hdr], hdr)
558 continue
559
560 if '.' not in hdr:
561 # assume a c++ system include
562 continue
563
564 if hdr in EXTERNAL_DEPS:
565 external_deps.add(EXTERNAL_DEPS[hdr], hdr)
566 continue
567
568 if hdr.startswith('opencensus/'):
569 trail = hdr[len('opencensus/'):]
570 trail = trail[:trail.find('/')]
571 external_deps.add('opencensus-' + trail, hdr)
572 continue
573
574 if hdr.startswith('envoy/'):
575 path, file = os.path.split(hdr)
576 file = file.split('.')
577 path = path.split('/')
578 dep = '_'.join(path[:-1] + [file[1]])
579 deps.add(dep, hdr)
580 continue
581
582 if hdr.startswith('google/protobuf/') and not hdr.endswith('.upb.h'):
583 external_deps.add('protobuf_headers', hdr)
584 continue
585
586 if '/' not in hdr:
587 # assume a system include
588 continue
589
590 is_sys_include = False
591 for sys_path in [
592 'sys',
593 'arpa',
594 'gperftools',
595 'netinet',
596 'linux',
597 'android',
598 'mach',
599 'net',
600 'CoreFoundation',
601 ]:
602 if hdr.startswith(sys_path + '/'):
603 is_sys_include = True
604 break
605 if is_sys_include:
606 # assume a system include
607 continue
608
609 print("# ERROR: can't categorize header: %s used by %s" %
610 (hdr, library))
611 error = True
612
613 deps.remove(library)
614
615 deps = sorted(
616 deps.best(lambda x: SCORERS[args.score](x, original_deps[library])))
617 external_deps = sorted(
618 external_deps.best(lambda x: SCORERS[args.score]
619 (x, original_external_deps[library])))
620
621 return (library, error, deps, external_deps)
622
623
624 update_libraries = []
625 for library in sorted(consumes.keys()):
626 if library in no_update:
627 continue
628 if args.targets and library not in args.targets:
629 continue
630 update_libraries.append(library)
631 with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as p:
632 updated_libraries = p.map(make_library, update_libraries, 1)
633
634 error = False
635 for library, lib_error, deps, external_deps in updated_libraries:
636 if lib_error:
637 error = True
638 continue
639 buildozer_set_list('external_deps', external_deps, library, via='deps')
640 buildozer_set_list('deps', deps, library)
641
642 run_buildozer.run_buildozer(buildozer_commands)
643
644 if error:
645 sys.exit(1)