-
-
Notifications
You must be signed in to change notification settings - Fork 608
/
global_options.py
1957 lines (1756 loc) · 78.7 KB
/
global_options.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import enum
import importlib
import logging
import os
import re
import sys
import tempfile
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from pathlib import Path, PurePath
from typing import Any, Callable, Type, cast
from pants.base.build_environment import (
get_buildroot,
get_default_pants_config_file,
get_pants_cachedir,
is_in_container,
pants_version,
)
from pants.base.deprecated import deprecated_conditional
from pants.base.glob_match_error_behavior import GlobMatchErrorBehavior
from pants.engine.environment import CompleteEnvironment
from pants.engine.internals.native_engine import PyExecutor
from pants.option.custom_types import memory_size
from pants.option.errors import OptionsError
from pants.option.option_types import (
BoolOption,
DictOption,
DirOption,
EnumOption,
FloatOption,
IntOption,
MemorySizeOption,
StrListOption,
StrOption,
collect_options_info,
)
from pants.option.option_value_container import OptionValueContainer
from pants.option.options import Options
from pants.option.scope import GLOBAL_SCOPE
from pants.option.subsystem import Subsystem
from pants.util.dirutil import fast_relpath_optional
from pants.util.docutil import bin_name, doc_url
from pants.util.logging import LogLevel
from pants.util.memo import memoized_classmethod, memoized_property
from pants.util.ordered_set import FrozenOrderedSet, OrderedSet
from pants.util.osutil import CPU_COUNT
from pants.util.strutil import fmt_memory_size, softwrap
from pants.version import VERSION
logger = logging.getLogger(__name__)
# The time that leases are acquired for in the local store. Configured on the Python side
# in order to ease interaction with the StoreGCService, which needs to be aware of its value.
LOCAL_STORE_LEASE_TIME_SECS = 2 * 60 * 60
MEGABYTES = 1_000_000
GIGABYTES = 1_000 * MEGABYTES
class DynamicUIRenderer(Enum):
"""Which renderer to use for dyanmic UI."""
indicatif_spinner = "indicatif-spinner"
experimental_prodash = "experimental-prodash"
class UnmatchedBuildFileGlobs(Enum):
"""What to do when globs do not match in BUILD files."""
warn = "warn"
error = "error"
def to_glob_match_error_behavior(self) -> GlobMatchErrorBehavior:
return GlobMatchErrorBehavior(self.value)
class UnmatchedCliGlobs(Enum):
"""What to do when globs do not match in CLI args."""
ignore = "ignore"
warn = "warn"
error = "error"
def to_glob_match_error_behavior(self) -> GlobMatchErrorBehavior:
return GlobMatchErrorBehavior(self.value)
class OwnersNotFoundBehavior(Enum):
"""What to do when a file argument cannot be mapped to an owning target."""
ignore = "ignore"
warn = "warn"
error = "error"
def to_glob_match_error_behavior(self) -> GlobMatchErrorBehavior:
return GlobMatchErrorBehavior(self.value)
@enum.unique
class RemoteCacheWarningsBehavior(Enum):
ignore = "ignore"
first_only = "first_only"
backoff = "backoff"
@enum.unique
class AuthPluginState(Enum):
OK = "ok"
UNAVAILABLE = "unavailable"
@dataclass(frozen=True)
class AuthPluginResult:
"""The return type for a function specified via `[GLOBAL].remote_auth_plugin`.
The returned `store_headers` and `execution_headers` will replace whatever headers Pants would
have used normally, e.g. what is set with `[GLOBAL].remote_store_headers`. This allows you to control
the merge strategy if your plugin sets conflicting headers. Usually, you will want to preserve
the `initial_store_headers` and `initial_execution_headers` passed to the plugin.
If set, the returned `instance_name` will override `[GLOBAL].remote_instance_name`, `store_address`
will override `[GLOBAL].remote_store_address`, and `execution_address` will override
``[GLOBAL].remote_execution_address``. The store address and execution address must be prefixed with
`grpc://` or `grpcs://`.
"""
state: AuthPluginState
store_headers: dict[str, str]
execution_headers: dict[str, str]
store_address: str | None = None
execution_address: str | None = None
instance_name: str | None = None
expiration: datetime | None = None
plugin_name: str | None = None
def __post_init__(self) -> None:
def assert_valid_address(addr: str | None, field_name: str) -> None:
valid_schemes = [f"{scheme}://" for scheme in ("grpc", "grpcs")]
if addr and not any(addr.startswith(scheme) for scheme in valid_schemes):
name = self.plugin_name or ""
raise ValueError(
f"Invalid `{field_name}` in `AuthPluginResult` returned from "
f"`[GLOBAL].remote_auth_plugin` {name}. Must start with `grpc://` or `grpcs://`, but was "
f"{addr}."
)
assert_valid_address(self.store_address, "store_address")
assert_valid_address(self.execution_address, "execution_address")
@property
def is_available(self) -> bool:
return self.state == AuthPluginState.OK
@dataclass(frozen=True)
class DynamicRemoteOptions:
"""Options related to remote execution of processes which are computed dynamically."""
execution: bool
cache_read: bool
cache_write: bool
instance_name: str | None
store_address: str | None
execution_address: str | None
store_headers: dict[str, str]
execution_headers: dict[str, str]
parallelism: int
store_rpc_concurrency: int
cache_rpc_concurrency: int
execution_rpc_concurrency: int
def _validate_store_addr(self) -> None:
if self.store_address:
return
if self.cache_read:
raise OptionsError(
"The `[GLOBAL].remote_cache_read` option requires also setting the"
"`[GLOBAL].remote_store_address` option in order to work properly."
)
if self.cache_write:
raise OptionsError(
"The `[GLOBAL].remote_cache_write` option requires also setting the "
"`[GLOBAL].remote_store_address` option in order to work properly."
)
def _validate_exec_addr(self) -> None:
if not self.execution:
return
if not self.execution_address:
raise OptionsError(
"The `[GLOBAL].remote_execution` option requires also setting the "
"`[GLOBAL].remote_execution_address` option in order to work properly."
)
if not self.store_address:
raise OptionsError(
"The `[GLOBAL].remote_execution_address` option requires also setting the "
"`[GLOBAL].remote_store_address` option. Often these have the same value."
)
def __post_init__(self) -> None:
self._validate_store_addr()
self._validate_exec_addr()
@classmethod
def disabled(cls) -> DynamicRemoteOptions:
return cls(
execution=False,
cache_read=False,
cache_write=False,
instance_name=None,
store_address=None,
execution_address=None,
store_headers={},
execution_headers={},
parallelism=DEFAULT_EXECUTION_OPTIONS.process_execution_remote_parallelism,
store_rpc_concurrency=DEFAULT_EXECUTION_OPTIONS.remote_store_rpc_concurrency,
cache_rpc_concurrency=DEFAULT_EXECUTION_OPTIONS.remote_cache_rpc_concurrency,
execution_rpc_concurrency=DEFAULT_EXECUTION_OPTIONS.remote_execution_rpc_concurrency,
)
@classmethod
def _get_auth_plugin_from_option(cls, remote_auth_plugin_option_value: str) -> Callable:
if ":" not in remote_auth_plugin_option_value:
raise OptionsError(
"Invalid value for `--remote-auth-plugin`: "
f"{remote_auth_plugin_option_value}. Please use the format "
"`path.to.module:my_func`."
)
auth_plugin_path, auth_plugin_func = remote_auth_plugin_option_value.split(":")
auth_plugin_module = importlib.import_module(auth_plugin_path)
return cast(Callable, getattr(auth_plugin_module, auth_plugin_func))
@classmethod
def _use_oauth_token(cls, bootstrap_options: OptionValueContainer) -> DynamicRemoteOptions:
oauth_token = (
Path(bootstrap_options.remote_oauth_bearer_token_path).resolve().read_text().strip()
)
if set(oauth_token).intersection({"\n", "\r"}):
raise OptionsError(
f"OAuth bearer token path {bootstrap_options.remote_oauth_bearer_token_path} "
"must not contain multiple lines."
)
if bootstrap_options.remote_auth_plugin:
raise OptionsError(
"OAuth bearer token path can not be used when setting the `[GLOBAL].remote_auth_plugin` option"
)
token_header = {"authorization": f"Bearer {oauth_token}"}
execution = cast(bool, bootstrap_options.remote_execution)
cache_read = cast(bool, bootstrap_options.remote_cache_read)
cache_write = cast(bool, bootstrap_options.remote_cache_write)
store_address = cast("str | None", bootstrap_options.remote_store_address)
execution_address = cast("str | None", bootstrap_options.remote_execution_address)
instance_name = cast("str | None", bootstrap_options.remote_instance_name)
execution_headers = cast("dict[str, str]", bootstrap_options.remote_execution_headers)
store_headers = cast("dict[str, str]", bootstrap_options.remote_store_headers)
parallelism = cast(int, bootstrap_options.process_execution_remote_parallelism)
store_rpc_concurrency = cast(int, bootstrap_options.remote_store_rpc_concurrency)
cache_rpc_concurrency = cast(int, bootstrap_options.remote_cache_rpc_concurrency)
execution_rpc_concurrency = cast(int, bootstrap_options.remote_execution_rpc_concurrency)
execution_headers.update(token_header)
store_headers.update(token_header)
return cls(
execution=execution,
cache_read=cache_read,
cache_write=cache_write,
instance_name=instance_name,
store_address=cls._normalize_address(store_address),
execution_address=cls._normalize_address(execution_address),
store_headers=store_headers,
execution_headers=execution_headers,
parallelism=parallelism,
store_rpc_concurrency=store_rpc_concurrency,
cache_rpc_concurrency=cache_rpc_concurrency,
execution_rpc_concurrency=execution_rpc_concurrency,
)
@classmethod
def from_options(
cls,
full_options: Options,
env: CompleteEnvironment,
prior_result: AuthPluginResult | None = None,
remote_auth_plugin_func: Callable | None = None,
) -> tuple[DynamicRemoteOptions, AuthPluginResult | None]:
bootstrap_options = full_options.bootstrap_option_values()
assert bootstrap_options is not None
execution = cast(bool, bootstrap_options.remote_execution)
cache_read = cast(bool, bootstrap_options.remote_cache_read)
cache_write = cast(bool, bootstrap_options.remote_cache_write)
if not (execution or cache_read or cache_write):
return cls.disabled(), None
if (
bootstrap_options.remote_auth_plugin
and bootstrap_options.remote_oauth_bearer_token_path
):
raise OptionsError(
"Both `[GLOBAL].remote_auth_plugin` and `[GLOBAL].remote_auth_plugin` `[GLOBAL].remote_oauth_bearer_token_path` are set. This is not supported. Only one of those should be set in order to provide auth information for remote cache."
)
if bootstrap_options.remote_oauth_bearer_token_path:
return cls._use_oauth_token(bootstrap_options), None
if bootstrap_options.remote_auth_plugin or remote_auth_plugin_func is not None:
return cls._use_auth_plugin(
bootstrap_options,
full_options=full_options,
env=env,
prior_result=prior_result,
remote_auth_plugin_func_from_entry_point=remote_auth_plugin_func,
)
return cls._use_no_auth(bootstrap_options), None
@classmethod
def _use_no_auth(cls, bootstrap_options: OptionValueContainer) -> DynamicRemoteOptions:
execution = cast(bool, bootstrap_options.remote_execution)
cache_read = cast(bool, bootstrap_options.remote_cache_read)
cache_write = cast(bool, bootstrap_options.remote_cache_write)
store_address = cast("str | None", bootstrap_options.remote_store_address)
execution_address = cast("str | None", bootstrap_options.remote_execution_address)
instance_name = cast("str | None", bootstrap_options.remote_instance_name)
execution_headers = cast("dict[str, str]", bootstrap_options.remote_execution_headers)
store_headers = cast("dict[str, str]", bootstrap_options.remote_store_headers)
parallelism = cast(int, bootstrap_options.process_execution_remote_parallelism)
store_rpc_concurrency = cast(int, bootstrap_options.remote_store_rpc_concurrency)
cache_rpc_concurrency = cast(int, bootstrap_options.remote_cache_rpc_concurrency)
execution_rpc_concurrency = cast(int, bootstrap_options.remote_execution_rpc_concurrency)
return cls(
execution=execution,
cache_read=cache_read,
cache_write=cache_write,
instance_name=instance_name,
store_address=cls._normalize_address(store_address),
execution_address=cls._normalize_address(execution_address),
store_headers=store_headers,
execution_headers=execution_headers,
parallelism=parallelism,
store_rpc_concurrency=store_rpc_concurrency,
cache_rpc_concurrency=cache_rpc_concurrency,
execution_rpc_concurrency=execution_rpc_concurrency,
)
@classmethod
def _use_auth_plugin(
cls,
bootstrap_options: OptionValueContainer,
full_options: Options,
env: CompleteEnvironment,
prior_result: AuthPluginResult | None,
remote_auth_plugin_func_from_entry_point: Callable | None,
) -> tuple[DynamicRemoteOptions, AuthPluginResult | None]:
auth_plugin_result: AuthPluginResult | None = None
if not remote_auth_plugin_func_from_entry_point:
remote_auth_plugin_func = cls._get_auth_plugin_from_option(
bootstrap_options.remote_auth_plugin
)
else:
remote_auth_plugin_func = remote_auth_plugin_func_from_entry_point
if bootstrap_options.remote_auth_plugin:
raise OptionsError(
"remote auth plugin already provided via entry point of a plugin. `[GLOBAL].remote_auth_plugin` should not be specified in options."
)
execution = cast(bool, bootstrap_options.remote_execution)
cache_read = cast(bool, bootstrap_options.remote_cache_read)
cache_write = cast(bool, bootstrap_options.remote_cache_write)
store_address = cast("str | None", bootstrap_options.remote_store_address)
execution_address = cast("str | None", bootstrap_options.remote_execution_address)
instance_name = cast("str | None", bootstrap_options.remote_instance_name)
execution_headers = cast("dict[str, str]", bootstrap_options.remote_execution_headers)
store_headers = cast("dict[str, str]", bootstrap_options.remote_store_headers)
parallelism = cast(int, bootstrap_options.process_execution_remote_parallelism)
store_rpc_concurrency = cast(int, bootstrap_options.remote_store_rpc_concurrency)
cache_rpc_concurrency = cast(int, bootstrap_options.remote_cache_rpc_concurrency)
execution_rpc_concurrency = cast(int, bootstrap_options.remote_execution_rpc_concurrency)
auth_plugin_result = cast(
AuthPluginResult,
remote_auth_plugin_func(
initial_execution_headers=execution_headers,
initial_store_headers=store_headers,
options=full_options,
env=dict(env),
prior_result=prior_result,
),
)
plugin_name = (
auth_plugin_result.plugin_name
or bootstrap_options.remote_auth_plugin
or f"{remote_auth_plugin_func.__module__}.{remote_auth_plugin_func.__name__}"
)
if not auth_plugin_result.is_available:
# NB: This is debug because we expect plugins to log more informative messages.
logger.debug(
f"Disabling remote caching and remote execution because authentication was not available via the plugin {plugin_name} (from `[GLOBAL].remote_auth_plugin`)."
)
return cls.disabled(), None
logger.debug(
f"`[GLOBAL].remote_auth_plugin` {plugin_name} succeeded. Remote caching/execution will be attempted."
)
execution_headers = auth_plugin_result.execution_headers
store_headers = auth_plugin_result.store_headers
plugin_provided_opt_log = "Setting `[GLOBAL].remote_{opt}` is not needed and will be ignored since it is provided by the auth plugin: {plugin_name}."
if auth_plugin_result.instance_name is not None:
if instance_name is not None:
logger.warning(
plugin_provided_opt_log.format(opt="instance_name", plugin_name=plugin_name)
)
instance_name = auth_plugin_result.instance_name
if auth_plugin_result.store_address is not None:
if store_address is not None:
logger.warning(
plugin_provided_opt_log.format(opt="store_address", plugin_name=plugin_name)
)
store_address = auth_plugin_result.store_address
if auth_plugin_result.execution_address is not None:
if execution_address is not None:
logger.warning(
plugin_provided_opt_log.format(opt="execution_address", plugin_name=plugin_name)
)
execution_address = auth_plugin_result.execution_address
opts = cls(
execution=execution,
cache_read=cache_read,
cache_write=cache_write,
instance_name=instance_name,
store_address=cls._normalize_address(store_address),
execution_address=cls._normalize_address(execution_address),
store_headers=store_headers,
execution_headers=execution_headers,
parallelism=parallelism,
store_rpc_concurrency=store_rpc_concurrency,
cache_rpc_concurrency=cache_rpc_concurrency,
execution_rpc_concurrency=execution_rpc_concurrency,
)
return opts, auth_plugin_result
@classmethod
def _normalize_address(cls, address: str | None) -> str | None:
# NB: Tonic expects the schemes `http` and `https`, even though they are gRPC requests.
# We validate that users set `grpc` and `grpcs` in the options system / plugin for clarity,
# but then normalize to `http`/`https`.
return re.sub(r"^grpc", "http", address) if address else None
@dataclass(frozen=True)
class ExecutionOptions:
"""A collection of all options related to (remote) execution of processes.
TODO: These options should move to a Subsystem once we add support for "bootstrap" Subsystems (ie,
allowing Subsystems to be consumed before the Scheduler has been created).
"""
remote_execution: bool
remote_cache_read: bool
remote_cache_write: bool
remote_instance_name: str | None
remote_ca_certs_path: str | None
process_cleanup: bool
local_cache: bool
process_execution_local_parallelism: int
process_execution_local_enable_nailgun: bool
process_execution_remote_parallelism: int
process_execution_cache_namespace: str | None
process_execution_graceful_shutdown_timeout: int
process_total_child_memory_usage: int | None
process_per_child_memory_usage: int
remote_store_address: str | None
remote_store_headers: dict[str, str]
remote_store_chunk_bytes: Any
remote_store_chunk_upload_timeout_seconds: int
remote_store_rpc_retries: int
remote_store_rpc_concurrency: int
remote_store_batch_api_size_limit: int
remote_cache_eager_fetch: bool
remote_cache_warnings: RemoteCacheWarningsBehavior
remote_cache_rpc_concurrency: int
remote_cache_read_timeout_millis: int
remote_execution_address: str | None
remote_execution_extra_platform_properties: list[str]
remote_execution_headers: dict[str, str]
remote_execution_overall_deadline_secs: int
remote_execution_rpc_concurrency: int
@classmethod
def from_options(
cls,
bootstrap_options: OptionValueContainer,
dynamic_remote_options: DynamicRemoteOptions,
) -> ExecutionOptions:
return cls(
# Remote execution strategy.
remote_execution=dynamic_remote_options.execution,
remote_cache_read=dynamic_remote_options.cache_read,
remote_cache_write=dynamic_remote_options.cache_write,
# General remote setup.
remote_instance_name=dynamic_remote_options.instance_name,
remote_ca_certs_path=bootstrap_options.remote_ca_certs_path,
# Process execution setup.
process_cleanup=bootstrap_options.process_cleanup,
local_cache=bootstrap_options.local_cache,
process_execution_local_parallelism=bootstrap_options.process_execution_local_parallelism,
process_execution_remote_parallelism=dynamic_remote_options.parallelism,
process_execution_cache_namespace=bootstrap_options.process_execution_cache_namespace,
process_execution_graceful_shutdown_timeout=bootstrap_options.process_execution_graceful_shutdown_timeout,
process_execution_local_enable_nailgun=bootstrap_options.process_execution_local_enable_nailgun,
process_total_child_memory_usage=bootstrap_options.process_total_child_memory_usage,
process_per_child_memory_usage=bootstrap_options.process_per_child_memory_usage,
# Remote store setup.
remote_store_address=dynamic_remote_options.store_address,
remote_store_headers=dynamic_remote_options.store_headers,
remote_store_chunk_bytes=bootstrap_options.remote_store_chunk_bytes,
remote_store_chunk_upload_timeout_seconds=bootstrap_options.remote_store_chunk_upload_timeout_seconds,
remote_store_rpc_retries=bootstrap_options.remote_store_rpc_retries,
remote_store_rpc_concurrency=dynamic_remote_options.store_rpc_concurrency,
remote_store_batch_api_size_limit=bootstrap_options.remote_store_batch_api_size_limit,
# Remote cache setup.
remote_cache_eager_fetch=bootstrap_options.remote_cache_eager_fetch,
remote_cache_warnings=bootstrap_options.remote_cache_warnings,
remote_cache_rpc_concurrency=dynamic_remote_options.cache_rpc_concurrency,
remote_cache_read_timeout_millis=bootstrap_options.remote_cache_read_timeout_millis,
# Remote execution setup.
remote_execution_address=dynamic_remote_options.execution_address,
remote_execution_extra_platform_properties=bootstrap_options.remote_execution_extra_platform_properties,
remote_execution_headers=dynamic_remote_options.execution_headers,
remote_execution_overall_deadline_secs=bootstrap_options.remote_execution_overall_deadline_secs,
remote_execution_rpc_concurrency=dynamic_remote_options.execution_rpc_concurrency,
)
@dataclass(frozen=True)
class LocalStoreOptions:
"""A collection of all options related to the local store.
TODO: These options should move to a Subsystem once we add support for "bootstrap" Subsystems (ie,
allowing Subsystems to be consumed before the Scheduler has been created).
"""
store_dir: str = os.path.join(get_pants_cachedir(), "lmdb_store")
processes_max_size_bytes: int = 16 * GIGABYTES
files_max_size_bytes: int = 256 * GIGABYTES
directories_max_size_bytes: int = 16 * GIGABYTES
shard_count: int = 16
def target_total_size_bytes(self) -> int:
"""Returns the target total size of all of the stores.
The `max_size` values are caps on the total size of each store: the "target" size
is the size that garbage collection will attempt to shrink the stores to each time
it runs.
NB: This value is not currently configurable, but that could be desirable in the future.
"""
max_total_size_bytes = (
self.processes_max_size_bytes
+ self.files_max_size_bytes
+ self.directories_max_size_bytes
)
return max_total_size_bytes // 10
@classmethod
def from_options(cls, options: OptionValueContainer) -> LocalStoreOptions:
return cls(
store_dir=str(Path(options.local_store_dir).resolve()),
processes_max_size_bytes=options.local_store_processes_max_size_bytes,
files_max_size_bytes=options.local_store_files_max_size_bytes,
directories_max_size_bytes=options.local_store_directories_max_size_bytes,
shard_count=options.local_store_shard_count,
)
_PER_CHILD_MEMORY_USAGE = "512MiB"
DEFAULT_EXECUTION_OPTIONS = ExecutionOptions(
# Remote execution strategy.
remote_execution=False,
remote_cache_read=False,
remote_cache_write=False,
# General remote setup.
remote_instance_name=None,
remote_ca_certs_path=None,
# Process execution setup.
process_total_child_memory_usage=None,
process_per_child_memory_usage=memory_size(_PER_CHILD_MEMORY_USAGE),
process_execution_local_parallelism=CPU_COUNT,
process_execution_remote_parallelism=128,
process_execution_cache_namespace=None,
process_cleanup=True,
local_cache=True,
process_execution_local_enable_nailgun=True,
process_execution_graceful_shutdown_timeout=3,
# Remote store setup.
remote_store_address=None,
remote_store_headers={
"user-agent": f"pants/{VERSION}",
},
remote_store_chunk_bytes=1024 * 1024,
remote_store_chunk_upload_timeout_seconds=60,
remote_store_rpc_retries=2,
remote_store_rpc_concurrency=128,
remote_store_batch_api_size_limit=4194304,
# Remote cache setup.
remote_cache_eager_fetch=True,
remote_cache_warnings=RemoteCacheWarningsBehavior.backoff,
remote_cache_rpc_concurrency=128,
remote_cache_read_timeout_millis=1500,
# Remote execution setup.
remote_execution_address=None,
remote_execution_extra_platform_properties=[],
remote_execution_headers={
"user-agent": f"pants/{VERSION}",
},
remote_execution_overall_deadline_secs=60 * 60, # one hour
remote_execution_rpc_concurrency=128,
)
DEFAULT_LOCAL_STORE_OPTIONS = LocalStoreOptions()
class LogLevelOption(EnumOption[LogLevel, LogLevel]):
"""The `--level` option.
This is a dedicated class because it's the only option where we allow both the short flag `-l`
and the long flag `--level`.
"""
def __new__(cls) -> LogLevelOption:
self = super().__new__(
cls, # type: ignore[arg-type]
default=LogLevel.INFO,
daemon=True,
help="Set the logging level.",
)
self._flag_names = ("-l", "--level")
return self # type: ignore[return-value]
class BootstrapOptions:
"""The set of options necessary to create a Scheduler.
If an option is not consumed during creation of a Scheduler, it should be a property of
GlobalOptions instead. Either way these options are injected into the GlobalOptions, which is
how they should be accessed (as normal global-scope options).
Their status as "bootstrap options" is only pertinent during option registration.
"""
_default_distdir_name = "dist"
_default_rel_distdir = f"/{_default_distdir_name}/"
backend_packages = StrListOption(
advanced=True,
help=softwrap(
"""
Register functionality from these backends.
The backend packages must be present on the PYTHONPATH, typically because they are in
the Pants core dist, in a plugin dist, or available as sources in the repo.
"""
),
)
plugins = StrListOption(
advanced=True,
help=softwrap(
"""
Allow backends to be loaded from these plugins (usually released through PyPI).
The default backends for each plugin will be loaded automatically. Other backends
in a plugin can be loaded by listing them in `backend_packages` in the
`[GLOBAL]` scope.
"""
),
)
plugins_force_resolve = BoolOption(
advanced=True,
default=False,
help="Re-resolve plugins, even if previously resolved.",
)
level = LogLevelOption()
show_log_target = BoolOption(
default=False,
daemon=True,
advanced=True,
help=softwrap(
"""
Display the target where a log message originates in that log message's output.
This can be helpful when paired with --log-levels-by-target.
"""
),
)
log_levels_by_target = DictOption[str](
daemon=True,
advanced=True,
help=softwrap(
"""
Set a more specific logging level for one or more logging targets. The names of
logging targets are specified in log strings when the --show-log-target option is set.
The logging levels are one of: "error", "warn", "info", "debug", "trace".
All logging targets not specified here use the global log level set with --level. For example,
you can set `--log-levels-by-target='{"workunit_store": "info", "pants.engine.rules": "warn"}'`.
"""
),
)
log_show_rust_3rdparty = BoolOption(
default=False,
daemon=True,
advanced=True,
help="Whether to show/hide logging done by 3rdparty Rust crates used by the Pants engine.",
)
ignore_warnings = StrListOption(
daemon=True,
advanced=True,
help=softwrap(
"""
Ignore logs and warnings matching these strings.
Normally, Pants will look for literal matches from the start of the log/warning
message, but you can prefix the ignore with `$regex$` for Pants to instead treat
your string as a regex pattern. For example:
ignore_warnings = [
"DEPRECATED: option 'config' in scope 'flake8' will be removed",
'$regex$:No files\\s*'
]
"""
),
)
pants_version = StrOption(
advanced=True,
default=pants_version(),
default_help_repr="<pants_version>",
daemon=True,
help=softwrap(
f"""
Use this Pants version. Note that Pants only uses this to verify that you are
using the requested version, as Pants cannot dynamically change the version it
is using once the program is already running.
If you use the `{bin_name()}` script from {doc_url('installation')}, however, changing
the value in your `pants.toml` will cause the new version to be installed and run automatically.
Run `{bin_name()} --version` to check what is being used.
"""
),
)
pants_bin_name = StrOption(
advanced=True,
default="./pants", # noqa: PANTSBIN
help="The name of the script or binary used to invoke Pants. "
"Useful when printing help messages.",
)
pants_workdir = StrOption(
advanced=True,
metavar="<dir>",
default=lambda _: os.path.join(get_buildroot(), ".pants.d"),
daemon=True,
help="Write intermediate logs and output files to this dir.",
)
pants_physical_workdir_base = StrOption(
advanced=True,
metavar="<dir>",
default=None,
daemon=True,
help=softwrap(
"""
When set, a base directory in which to store `--pants-workdir` contents.
If this option is a set, the workdir will be created as symlink into a
per-workspace subdirectory.
"""
),
)
pants_distdir = StrOption(
advanced=True,
metavar="<dir>",
default=lambda _: os.path.join(get_buildroot(), "dist"),
help="Write end products, such as the results of `./pants package`, to this dir.", # noqa: PANTSBIN
)
pants_subprocessdir = StrOption(
advanced=True,
default=lambda _: os.path.join(get_buildroot(), ".pids"),
daemon=True,
help=softwrap(
"""
The directory to use for tracking subprocess metadata. This should
live outside of the dir used by `pants_workdir` to allow for tracking
subprocesses that outlive the workdir data.
"""
),
)
pants_config_files = StrListOption(
advanced=True,
# NB: We don't fingerprint the list of config files, because the content of the config
# files independently affects fingerprints.
fingerprint=False,
default=lambda _: [get_default_pants_config_file()],
help=softwrap(
"""
Paths to Pants config files. This may only be set through the environment variable
`PANTS_CONFIG_FILES` and the command line argument `--pants-config-files`; it will
be ignored if in a config file like `pants.toml`.
"""
),
)
pantsrc = BoolOption(
advanced=True,
default=True,
# NB: See `--pants-config-files`.
fingerprint=False,
help="Use pantsrc files located at the paths specified in the global option `pantsrc_files`.",
)
pantsrc_files = StrListOption(
advanced=True,
metavar="<path>",
# NB: See `--pants-config-files`.
fingerprint=False,
default=["/etc/pantsrc", "~/.pants.rc", ".pants.rc"],
help="Override config with values from these files, using syntax matching that of `--pants-config-files`.",
)
pythonpath = StrListOption(
advanced=True,
help=softwrap(
"""
Add these directories to PYTHONPATH to search for plugins. This does not impact the
PYTHONPATH used by Pants when running your Python code.
"""
),
)
spec_files = StrListOption(
# NB: We don't fingerprint spec files because the content of the files independently
# affects fingerprints.
fingerprint=False,
help=softwrap(
"""
Read additional specs (target addresses, files, and/or globs), one per line, from these
files.
"""
),
)
verify_config = BoolOption(
default=True,
advanced=True,
help="Verify that all config file values correspond to known options.",
)
stats_record_option_scopes = StrListOption(
advanced=True,
default=["*"],
help=softwrap(
"""
Option scopes to record in stats on run completion.
Options may be selected by joining the scope and the option with a ^ character,
i.e. to get option `pantsd` in the GLOBAL scope, you'd pass `GLOBAL^pantsd`.
Add a '*' to the list to capture all known scopes.
"""
),
)
pants_ignore = StrListOption(
advanced=True,
default=[".*/", _default_rel_distdir, "__pycache__"],
help=softwrap(
"""
Paths to ignore for all filesystem operations performed by pants
(e.g. BUILD file scanning, glob matching, etc).
Patterns use the gitignore syntax (https://git-scm.com/docs/gitignore).
The `pants_distdir` and `pants_workdir` locations are automatically ignored.
`pants_ignore` can be used in tandem with `pants_ignore_use_gitignore`; any rules
specified here are applied after rules specified in a .gitignore file.
"""
),
)
pants_ignore_use_gitignore = BoolOption(
advanced=True,
default=True,
help=softwrap(
"""
Make use of a root .gitignore file when determining whether to ignore filesystem
operations performed by Pants. If used together with `--pants-ignore`, any exclude/include
patterns specified there apply after .gitignore rules.
"""
),
)
# These logging options are registered in the bootstrap phase so that plugins can log during
# registration and not so that their values can be interpolated in configs.
logdir = StrOption(
advanced=True,
default=None,
metavar="<dir>",
daemon=True,
help="Write logs to files under this directory.",
)
pantsd = BoolOption(
default=True,
daemon=True,
help=softwrap(
"""
Enables use of the Pants daemon (pantsd). pantsd can significantly improve
runtime performance by lowering per-run startup cost, and by memoizing filesystem
operations and rule execution.
"""
),
)
# Whether or not to make necessary arrangements to have concurrent runs in pants.
# In practice, this means that if this is set, a run will not even try to use pantsd.
# NB: Eventually, we would like to deprecate this flag in favor of making pantsd runs parallelizable.
concurrent = BoolOption(
default=False,
help=softwrap(
"""
Enable concurrent runs of Pants. Without this enabled, Pants will
start up all concurrent invocations (e.g. in other terminals) without pantsd.
Enabling this option requires parallel Pants invocations to block on the first.
"""
),
)
# NB: We really don't want this option to invalidate the daemon, because different clients might have
# different needs. For instance, an IDE might have a very long timeout because it only wants to refresh
# a project in the background, while a user might want a shorter timeout for interactivity.
pantsd_timeout_when_multiple_invocations = FloatOption(
advanced=True,
default=60.0,
help=softwrap(
"""
The maximum amount of time to wait for the invocation to start until
raising a timeout exception.
Because pantsd currently does not support parallel runs,
any prior running Pants command must be finished for the current one to start.
To never timeout, use the value -1.
"""
),
)
pantsd_max_memory_usage = MemorySizeOption(
advanced=True,
default=memory_size("1GiB"),
default_help_repr="1GiB",
help=softwrap(
"""
The maximum memory usage of the pantsd process.
When the maximum memory is exceeded, the daemon will restart gracefully,
although all previous in-memory caching will be lost. Setting too low means that
you may miss out on some caching, whereas setting too high may over-consume
resources and may result in the operating system killing Pantsd due to memory
overconsumption (e.g. via the OOM killer).
You can suffix with `GiB`, `MiB`, `KiB`, or `B` to indicate the unit, e.g.
`2GiB` or `2.12GiB`. A bare number will be in bytes.
There is at most one pantsd process per workspace.
"""
),
)
# These facilitate configuring the native engine.
print_stacktrace = BoolOption(
advanced=True,
default=False,
help="Print the full exception stack trace for any errors.",
)
engine_visualize_to = DirOption(
advanced=True,
default=None,
help=softwrap(
"""
A directory to write execution and rule graphs to as `dot` files. The contents
of the directory will be overwritten if any filenames collide.
"""
),
)
# Pants Daemon options.
pantsd_nailgun_port = IntOption(
# TODO: The name "pailgun" is likely historical, and this should be renamed to "nailgun".
"--pantsd-pailgun-port",
advanced=True,
default=0,
daemon=True,
help="The port to bind the Pants nailgun server to. Defaults to a random port.",
)
pantsd_invalidation_globs = StrListOption(
advanced=True,
daemon=True,
help=softwrap(
"""
Filesystem events matching any of these globs will trigger a daemon restart.
Pants's own code, plugins, and `--pants-config-files` are inherently invalidated.
"""
),