Debian Codegraph @

bazel/grpc_build_system.bzl

raw
1 # Copyright 2016 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 #
16 # This is for the gRPC build system. This isn't intended to be used outsite of
17 # the BUILD file for gRPC. It contains the mapping for the template system we
18 # use to generate other platform's build system files.
19 #
20 # Please consider that there should be a high bar for additions and changes to
21 # this file.
22 # Each rule listed must be re-written for Google's internal build system, and
23 # each change must be ported from one to the other.
24 #
25
26 """
27 Contains macros used throughout the repo.
28 """
29
30 load("//bazel:cc_grpc_library.bzl", "cc_grpc_library")
31 load("//bazel:copts.bzl", "GRPC_DEFAULT_COPTS")
32 load("//bazel:experiments.bzl", "EXPERIMENTS")
33 load("@upb//bazel:upb_proto_library.bzl", "upb_proto_library", "upb_proto_reflection_library")
34 load("@build_bazel_rules_apple//apple:ios.bzl", "ios_unit_test")
35 load("@build_bazel_rules_apple//apple/testing/default_runner:ios_test_runner.bzl", "ios_test_runner")
36
37 # The set of pollers to test against if a test exercises polling
38 POLLERS = ["epoll1", "poll"]
39
40 # The set of known EventEngines to test
41 EVENT_ENGINES = {"default": {"tags": []}}
42
43 def if_not_windows(a):
44 return select({
45 "//:windows": [],
46 "//:windows_msvc": [],
47 "//conditions:default": a,
48 })
49
50 def if_windows(a):
51 return select({
52 "//:windows": a,
53 "//:windows_msvc": a,
54 "//conditions:default": [],
55 })
56
57 def _get_external_deps(external_deps):
58 ret = []
59 for dep in external_deps:
60 if dep == "address_sorting":
61 ret.append("//third_party/address_sorting")
62 elif dep == "xxhash":
63 ret.append("//third_party/xxhash")
64 elif dep == "cares":
65 ret += select({
66 "//:grpc_no_ares": [],
67 "//conditions:default": ["//external:cares"],
68 })
69 elif dep == "cronet_c_for_grpc":
70 ret.append("//third_party/objective_c/Cronet:cronet_c_for_grpc")
71 elif dep.startswith("absl/"):
72 ret.append("@com_google_absl//" + dep)
73 else:
74 ret.append("//external:" + dep)
75 return ret
76
77 def _update_visibility(visibility):
78 if visibility == None:
79 return None
80
81 # Visibility rules prefixed with '@grpc:' are used to flag different visibility rule
82 # classes upstream.
83 PUBLIC = ["//visibility:public"]
84 PRIVATE = ["//:__subpackages__"]
85 VISIBILITY_TARGETS = {
86 "alt_grpc++_base_legacy": PRIVATE,
87 "alt_grpc_base_legacy": PRIVATE,
88 "alt_grpc++_base_unsecure_legacy": PRIVATE,
89 "alts_frame_protector": PRIVATE,
90 "channelz": PRIVATE,
91 "client_channel": PRIVATE,
92 "cli": PRIVATE,
93 "debug_location": PRIVATE,
94 "endpoint_tests": PRIVATE,
95 "exec_ctx": PRIVATE,
96 "grpclb": PRIVATE,
97 "grpc_opencensus_plugin": PUBLIC,
98 "grpcpp_gcp_observability": PUBLIC,
99 "grpc_resolver_fake": PRIVATE,
100 "grpc++_test": PRIVATE,
101 "http": PRIVATE,
102 "httpcli": PRIVATE,
103 "iomgr_timer": PRIVATE,
104 "public": PUBLIC,
105 "ref_counted_ptr": PRIVATE,
106 "trace": PRIVATE,
107 "tsi_interface": PRIVATE,
108 "tsi": PRIVATE,
109 "xds": PRIVATE,
110 "xds_client_core": PRIVATE,
111 }
112 final_visibility = []
113 for rule in visibility:
114 if rule.startswith("@grpc:"):
115 for replacement in VISIBILITY_TARGETS[rule[len("@grpc:"):]]:
116 final_visibility.append(replacement)
117 else:
118 final_visibility.append(rule)
119 return [x for x in final_visibility]
120
121 def grpc_cc_library(
122 name,
123 srcs = [],
124 public_hdrs = [],
125 hdrs = [],
126 external_deps = [],
127 defines = [],
128 deps = [],
129 select_deps = None,
130 standalone = False,
131 language = "C++",
132 testonly = False,
133 visibility = None,
134 alwayslink = 0,
135 data = [],
136 tags = [],
137 linkstatic = False):
138 """An internal wrapper around cc_library.
139
140 Args:
141 name: The name of the library.
142 srcs: The source files.
143 public_hdrs: The public headers.
144 hdrs: The headers.
145 external_deps: External depdendencies to be resolved.
146 defines: Build defines to use.
147 deps: cc_library deps.
148 select_deps: deps included conditionally.
149 standalone: Unused.
150 language: The language of the library, e.g. C, C++.
151 testonly: Whether the target is for tests only.
152 visibility: The visibility of the target.
153 alwayslink: Whether to enable alwayslink on the cc_library.
154 data: Data dependencies.
155 tags: Tags to apply to the rule.
156 linkstatic: Whether to enable linkstatic on the cc_library.
157 """
158 visibility = _update_visibility(visibility)
159 copts = []
160 if language.upper() == "C":
161 copts = copts + if_not_windows(["-std=c11"])
162 linkopts = if_not_windows(["-pthread"]) + if_windows(["-defaultlib:ws2_32.lib"])
163 if select_deps:
164 for select_deps_entry in select_deps:
165 deps += select(select_deps_entry)
166 native.cc_library(
167 name = name,
168 srcs = srcs,
169 defines = defines +
170 select({
171 "//:grpc_no_ares": ["GRPC_ARES=0"],
172 "//conditions:default": [],
173 }) +
174 select({
175 "//:remote_execution": ["GRPC_PORT_ISOLATED_RUNTIME=1"],
176 "//conditions:default": [],
177 }) +
178 select({
179 "//:grpc_allow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=1"],
180 "//:grpc_disallow_exceptions": ["GRPC_ALLOW_EXCEPTIONS=0"],
181 "//conditions:default": [],
182 }),
183 hdrs = hdrs + public_hdrs,
184 deps = deps + _get_external_deps(external_deps),
185 copts = GRPC_DEFAULT_COPTS + copts,
186 visibility = visibility,
187 testonly = testonly,
188 linkopts = linkopts,
189 includes = [
190 "include",
191 "src/core/ext/upb-generated", # Once upb code-gen issue is resolved, remove this.
192 "src/core/ext/upbdefs-generated", # Once upb code-gen issue is resolved, remove this.
193 ],
194 alwayslink = alwayslink,
195 data = data,
196 tags = tags,
197 linkstatic = linkstatic,
198 )
199
200 def grpc_proto_plugin(name, srcs = [], deps = []):
201 native.cc_binary(
202 name = name,
203 srcs = srcs,
204 deps = deps,
205 )
206
207 def grpc_proto_library(
208 name,
209 srcs = [],
210 deps = [],
211 well_known_protos = False,
212 has_services = True,
213 use_external = False,
214 generate_mocks = False):
215 cc_grpc_library(
216 name = name,
217 srcs = srcs,
218 deps = deps,
219 well_known_protos = well_known_protos,
220 proto_only = not has_services,
221 use_external = use_external,
222 generate_mocks = generate_mocks,
223 )
224
225 def ios_cc_test(
226 name,
227 tags = [],
228 **kwargs):
229 """An ios C++ test target.
230
231 Args:
232 name: The name of the test.
233 tags: The tags to apply to the test.
234 **kwargs: All other arguments to apply.
235 """
236 test_lib_ios = name + "_test_lib_ios"
237 ios_tags = tags + ["manual", "ios_cc_test"]
238 test_runner = "ios_x86_64_sim_runner_" + name
239 ios_test_runner(
240 name = test_runner,
241 device_type = "iPhone X",
242 )
243 if not any([t for t in tags if t.startswith("no_test_ios")]):
244 native.objc_library(
245 name = test_lib_ios,
246 srcs = kwargs.get("srcs"),
247 deps = kwargs.get("deps"),
248 copts = kwargs.get("copts"),
249 data = kwargs.get("data"),
250 tags = ios_tags,
251 alwayslink = 1,
252 testonly = 1,
253 )
254 ios_test_deps = [":" + test_lib_ios]
255 ios_unit_test(
256 name = name + "_on_ios",
257 size = kwargs.get("size"),
258 data = kwargs.get("data"),
259 tags = ios_tags,
260 minimum_os_version = "9.0",
261 runner = test_runner,
262 deps = ios_test_deps,
263 )
264
265 def expand_tests(name, srcs, deps, tags, args, exclude_pollers, uses_polling, uses_event_engine):
266 """Common logic used to parameterize tests for every poller and EventEngine and experiment.
267
268 Args:
269 name: base name of the test
270 srcs: source files
271 deps: base deps
272 tags: base tags
273 args: base args
274 exclude_pollers: list of poller names to exclude for this set of tests.
275 uses_polling: set to False if the test is not sensitive to polling methodology.
276 uses_event_engine: set to False if the test is not sensitive to
277 EventEngine implementation differences
278
279 Returns:
280 A list of dictionaries containing modified values of name, srcs, deps, tags, and args.
281 """
282 poller_config = []
283
284 if not uses_polling:
285 tags = tags + ["no_uses_polling"]
286
287 poller_config.append({
288 "name": name,
289 "srcs": srcs,
290 "deps": deps,
291 "tags": tags,
292 "args": args,
293 "env": {},
294 })
295 else:
296 # On linux we run the same test with the default EventEngine, once for each
297 # poller
298 for poller in POLLERS:
299 if poller in exclude_pollers:
300 continue
301 poller_config.append({
302 "name": name + "@poller=" + poller,
303 "srcs": srcs,
304 "deps": deps,
305 "tags": (tags + EVENT_ENGINES["default"]["tags"] + [
306 "no_windows",
307 "no_mac",
308 "bazel_only",
309 ]),
310 "args": args,
311 "env": {
312 "GRPC_POLL_STRATEGY": poller,
313 },
314 })
315
316 # Now generate one test for each subsequent EventEngine, all using the
317 # default poller. These tests will have `@engine=<name>` appended to the
318 # test target name. If a test target name has no `@engine=<name>` component,
319 # that indicates that the default EventEngine is being used.
320 if not uses_event_engine:
321 # The poller tests exercise the default engine on Linux. This test
322 # handles other platforms.
323 poller_config.append({
324 "name": name,
325 "srcs": srcs,
326 "deps": deps,
327 "tags": tags + ["no_linux"],
328 "args": args,
329 "env": {},
330 })
331 else:
332 for engine_name, engine in EVENT_ENGINES.items():
333 test_name = name + "@engine=" + engine_name
334 test_tags = tags + engine["tags"] + ["bazel_only"]
335 test_args = args + ["--engine=" + engine_name]
336 if engine_name == "default":
337 # The poller tests exercise the default engine on Linux.
338 # This test handles other platforms.
339 test_name = name
340 test_tags = tags + engine["tags"] + ["no_linux"]
341 test_args = args
342 poller_config.append({
343 "name": test_name,
344 "srcs": srcs,
345 "deps": deps,
346 "tags": test_tags,
347 "args": test_args,
348 "env": {},
349 })
350
351 experiments = {}
352 for mode, tag_to_experiments in EXPERIMENTS.items():
353 experiments[mode] = {}
354 for tag in tags:
355 if tag not in tag_to_experiments:
356 continue
357 for experiment in tag_to_experiments[tag]:
358 experiments[mode][experiment] = 1
359 experiments[mode] = list(experiments[mode].keys())
360
361 mode_config = {
362 # format: <mode>: (enabled_target_tags, disabled_target_tags)
363 "dbg": (["noopt"], ["nodbg"]),
364 "opt": (["nodbg"], ["noopt"]),
365 "on": (None, []),
366 "off": ([], None),
367 }
368
369 must_have_tags = [
370 # We don't run experiments on cmake builds
371 "bazel_only",
372 # Nor on windows
373 "no_windows",
374 # Nor on mac
375 "no_mac",
376 # Nor on arm64
377 "no_arm64",
378 ]
379 experiment_config = list(poller_config)
380 for mode, config in mode_config.items():
381 enabled_tags, disabled_tags = config
382 if enabled_tags != None:
383 for experiment in experiments[mode]:
384 for config in poller_config:
385 config = dict(config)
386 config["name"] = config["name"] + "@experiment=" + experiment
387 env = dict(config["env"])
388 env["GRPC_EXPERIMENTS"] = experiment
389 config["env"] = env
390 tags = config["tags"]
391 for tag in must_have_tags + enabled_tags:
392 if tag not in tags:
393 tags = tags + [tag]
394 config["tags"] = tags
395 experiment_config.append(config)
396 if disabled_tags != None:
397 for experiment in experiments[mode]:
398 for config in poller_config:
399 config = dict(config)
400 config["name"] = config["name"] + "@experiment=no_" + experiment
401 env = dict(config["env"])
402 env["GRPC_EXPERIMENTS"] = "-" + experiment
403 config["env"] = env
404 tags = config["tags"]
405 for tag in must_have_tags + disabled_tags:
406 if tag not in tags:
407 tags = tags + [tag]
408 config["tags"] = tags
409 experiment_config.append(config)
410 return experiment_config
411
412 def grpc_cc_test(name, srcs = [], deps = [], external_deps = [], args = [], data = [], uses_polling = True, language = "C++", size = "medium", timeout = None, tags = [], exec_compatible_with = [], exec_properties = {}, shard_count = None, flaky = None, copts = [], linkstatic = None, exclude_pollers = [], uses_event_engine = True):
413 """A cc_test target for use in the gRPC repo.
414
415 Args:
416 name: The name of the test.
417 srcs: The source files.
418 deps: The target deps.
419 external_deps: The external deps.
420 args: The args to supply to the test binary.
421 data: Data dependencies.
422 uses_polling: Whether the test uses polling.
423 language: The language of the test, e.g C, C++.
424 size: The size of the test.
425 timeout: The test timeout.
426 tags: The tags for the test.
427 exec_compatible_with: A list of constraint values that must be
428 satisifed for the platform.
429 exec_properties: A dictionary of strings that will be added to the
430 exec_properties of a platform selected for this target.
431 shard_count: The number of shards for this test.
432 flaky: Whether this test is flaky.
433 copts: Add these to the compiler invocation.
434 linkstatic: link the binary in static mode
435 exclude_pollers: list of poller names to exclude for this set of tests.
436 uses_event_engine: set to False if the test is not sensitive to
437 EventEngine implementation differences
438 """
439 if language.upper() == "C":
440 copts = copts + if_not_windows(["-std=c11"])
441
442 core_deps = deps + _get_external_deps(external_deps) + ["//test/core/util:grpc_suppressions"]
443
444 # Test args for all tests
445 test_args = {
446 "data": data,
447 "copts": GRPC_DEFAULT_COPTS + copts,
448 "linkopts": if_not_windows(["-pthread"]) + if_windows(["-defaultlib:ws2_32.lib"]),
449 "size": size,
450 "timeout": timeout,
451 "exec_compatible_with": exec_compatible_with,
452 "exec_properties": exec_properties,
453 "shard_count": shard_count,
454 "flaky": flaky,
455 "linkstatic": linkstatic,
456 }
457
458 if "grpc-fuzzer" not in tags:
459 ios_cc_test(
460 name = name,
461 srcs = srcs,
462 tags = tags,
463 deps = core_deps,
464 args = args,
465 **test_args
466 )
467
468 for poller_config in expand_tests(name, srcs, core_deps, tags, args, exclude_pollers, uses_polling, uses_event_engine):
469 native.cc_test(
470 name = poller_config["name"],
471 srcs = poller_config["srcs"],
472 deps = poller_config["deps"],
473 tags = poller_config["tags"],
474 args = poller_config["args"],
475 env = poller_config["env"],
476 **test_args
477 )
478
479 def grpc_cc_binary(name, srcs = [], deps = [], external_deps = [], args = [], data = [], language = "C++", testonly = False, linkshared = False, linkopts = [], tags = [], features = [], visibility = None):
480 """Generates a cc_binary for use in the gRPC repo.
481
482 Args:
483 name: The name of the target.
484 srcs: The source files.
485 deps: The dependencies.
486 external_deps: The external dependencies.
487 args: The arguments to supply to the binary.
488 data: The data dependencies.
489 language: The language of the binary, e.g. C, C++.
490 testonly: Whether the binary is for tests only.
491 linkshared: Enables linkshared on the binary.
492 linkopts: linkopts to supply to the cc_binary.
493 tags: Tags to apply to the target.
494 features: features to be supplied to the cc_binary.
495 visibility: The visibility of the target.
496 """
497 visibility = _update_visibility(visibility)
498 copts = []
499 if language.upper() == "C":
500 copts = ["-std=c11"]
501 native.cc_binary(
502 name = name,
503 srcs = srcs,
504 args = args,
505 data = data,
506 testonly = testonly,
507 linkshared = linkshared,
508 deps = deps + _get_external_deps(external_deps) + ["//test/core/util:grpc_suppressions"],
509 copts = GRPC_DEFAULT_COPTS + copts,
510 linkopts = if_not_windows(["-pthread"]) + linkopts,
511 tags = tags,
512 features = features,
513 )
514
515 # buildifier: disable=unnamed-macro
516 def grpc_generate_one_off_targets():
517 # In open-source, grpc_objc* libraries depend directly on //:grpc
518 native.alias(
519 name = "grpc_objc",
520 actual = "//:grpc",
521 )
522 native.config_setting(
523 name = "windows_other",
524 values = {"define": "GRPC_WINDOWS_OTHER=1"},
525 )
526
527 def grpc_generate_objc_one_off_targets():
528 pass
529
530 def grpc_sh_test(name, srcs = [], args = [], data = [], uses_polling = True, size = "medium", timeout = None, tags = [], exec_compatible_with = [], exec_properties = {}, shard_count = None, flaky = None, exclude_pollers = [], uses_event_engine = True):
531 """Execute an sh_test for every <poller> x <EventEngine> combination
532
533 Args:
534 name: The name of the test.
535 srcs: The source files.
536 args: The args to supply to the test binary.
537 data: Data dependencies.
538 uses_polling: Whether the test uses polling.
539 size: The size of the test.
540 timeout: The test timeout.
541 tags: The tags for the test.
542 exec_compatible_with: A list of constraint values that must be
543 satisifed for the platform.
544 exec_properties: A dictionary of strings that will be added to the
545 exec_properties of a platform selected for this target.
546 shard_count: The number of shards for this test.
547 flaky: Whether this test is flaky.
548 exclude_pollers: list of poller names to exclude for this set of tests.
549 uses_event_engine: set to False if the test is not sensitive to
550 EventEngine implementation differences
551 """
552 test_args = {
553 "data": data,
554 "size": size,
555 "timeout": timeout,
556 "exec_compatible_with": exec_compatible_with,
557 "exec_properties": exec_properties,
558 "shard_count": shard_count,
559 "flaky": flaky,
560 }
561
562 for poller_config in expand_tests(name, srcs, [], tags, args, exclude_pollers, uses_polling, uses_event_engine):
563 native.sh_test(
564 name = poller_config["name"],
565 srcs = poller_config["srcs"],
566 deps = poller_config["deps"],
567 tags = poller_config["tags"],
568 args = poller_config["args"],
569 env = poller_config["env"],
570 **test_args
571 )
572
573 def grpc_sh_binary(name, srcs, data = []):
574 native.sh_binary(
575 name = name,
576 srcs = srcs,
577 data = data,
578 )
579
580 def grpc_py_binary(
581 name,
582 srcs,
583 data = [],
584 deps = [],
585 external_deps = [],
586 testonly = False,
587 python_version = "PY2",
588 **kwargs):
589 native.py_binary(
590 name = name,
591 srcs = srcs,
592 testonly = testonly,
593 data = data,
594 deps = deps + _get_external_deps(external_deps),
595 python_version = python_version,
596 **kwargs
597 )
598
599 def grpc_package(name, visibility = "private", features = []):
600 """Creates a package.
601
602 Args:
603 name: The name of the target
604 visibility: The visibility of the target.
605 features: The features to enable.
606 """
607 if visibility == "tests":
608 visibility = ["//test:__subpackages__"]
609 elif visibility == "public":
610 visibility = ["//visibility:public"]
611 elif visibility == "private":
612 visibility = []
613 else:
614 fail("Unknown visibility " + visibility)
615
616 if len(visibility) != 0:
617 # buildifier: disable=native-package
618 native.package(
619 default_visibility = visibility,
620 features = features,
621 )
622
623 def grpc_objc_library(
624 name,
625 srcs = [],
626 hdrs = [],
627 non_arc_srcs = [],
628 textual_hdrs = [],
629 testonly = False,
630 data = [],
631 deps = [],
632 defines = [],
633 sdk_frameworks = [],
634 includes = [],
635 visibility = ["//visibility:public"]):
636 """The grpc version of objc_library, only used for the Objective-C library compilation
637
638 Args:
639 name: name of target
640 hdrs: public headers
641 srcs: all source files (.m)
642 non_arc_srcs: list of Objective-C files that DO NOT use ARC.
643 textual_hdrs: private headers
644 testonly: Whether the binary is for tests only.
645 data: any other bundle resources
646 defines: preprocessors
647 sdk_frameworks: sdks
648 includes: added to search path, always [the path to objc directory]
649 deps: dependencies
650 visibility: visibility, default to public
651 """
652
653 native.objc_library(
654 name = name,
655 hdrs = hdrs,
656 srcs = srcs,
657 non_arc_srcs = non_arc_srcs,
658 textual_hdrs = textual_hdrs,
659 copts = GRPC_DEFAULT_COPTS + ["-ObjC++", "-std=gnu++14"],
660 testonly = testonly,
661 data = data,
662 deps = deps,
663 defines = defines,
664 includes = includes,
665 sdk_frameworks = sdk_frameworks,
666 visibility = visibility,
667 )
668
669 def grpc_upb_proto_library(name, deps):
670 upb_proto_library(name = name, deps = deps)
671
672 def grpc_upb_proto_reflection_library(name, deps):
673 upb_proto_reflection_library(name = name, deps = deps)
674
675 # buildifier: disable=unnamed-macro
676 def python_config_settings():
677 native.config_setting(
678 name = "python3",
679 flag_values = {"@bazel_tools//tools/python:python_version": "PY3"},
680 )