-
Notifications
You must be signed in to change notification settings - Fork 28.8k
Expand file tree
/
Copy pathrunner_determinator.py
More file actions
784 lines (646 loc) · 27.7 KB
/
Copy pathrunner_determinator.py
File metadata and controls
784 lines (646 loc) · 27.7 KB
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
# flake8: noqa: G004
"""
This runner determinator is used to determine which set of runners to run a
GitHub job on. It uses the first comment of a GitHub issue (by default
https://github.com/pytorch/test-infra/issues/5132) to define the configuration
of which runners should be used to run which job.
The configuration has two parts, the settings and a list of opted-in users,
separated by a line containing "---". If the line is not present, the
settings are considered to be empty with only the second part, the user
list, defined.
The first part is a YAML block that defines the rollout settings. This can be
used to define any settings that are needed to determine which runners to use.
It's fields are defined by the RolloutSettings class below.
The second part is a list of users who are explicitly opted in to the LF fleet.
The user list is also a comma separated list of additional features or
experiments which the user could be opted in to.
The user list has the following rules:
- Users are GitHub usernames, which must start with the @ prefix
- Each user is also a comma-separated list of features/experiments to enable
- Each experiment can optionally include a per-user rollout percentage
using the syntax "experiment:percentage" (e.g. "lf:10" for 10% rollout)
- Without a percentage, opted-in experiments are enabled 100% of the time
- A "#" prefix opts the user out of all experiments
- A "-" prefix on an experiment opts the user out of that experiment
Example config:
# A list of experiments that can be opted into.
# This defines the behavior they'll induce when opted into.
# Expected syntax is:
# [experiment_name]: # Name of the experiment. Also used for the label prefix.
# rollout_perc: [int] # % of workflows to run with this experiment when users are not opted in.
experiments:
lf:
rollout_percent: 25
all_branches: false
default: true
---
# Opt-ins:
# Users can opt into the LF fleet by adding their GitHub username to this list
# and specifying experiments to enable in a comma-separated list.
# Optionally append :N to set a per-user rollout percentage (0-100).
# To always opt out of an experiment, prefix it with a "-".
# Experiments should be from the above list.
@User1,-lf,split_build
@User2,lf
@User3,split_build
@User4,lf,split_build:10
"""
import json
import logging
import os
import random
import re
from argparse import ArgumentParser
from collections.abc import Iterable
from functools import cache
from logging import LogRecord
from typing import Any, NamedTuple
from urllib.request import Request, urlopen
import yaml
from github import Auth, Github
from github.Issue import Issue
GITHUB_OUTPUT = os.getenv("GITHUB_OUTPUT", "")
GH_OUTPUT_KEY_AMI = "runner-ami"
GH_OUTPUT_KEY_LABEL_TYPE = "label-type"
GH_OUTPUT_KEY_AMD_SANDBOX_LABEL_TYPE = "amd-sandbox-label-type"
OPT_OUT_LABEL = "no-runner-experiments"
SETTING_EXPERIMENTS = "experiments"
# Sentinel in the per-experiment ``workflows`` allowlist meaning "all workflows".
WORKFLOW_ALLOWLIST_ALL = "ALL"
LF_FLEET_EXPERIMENT = "lf"
# The Meta (OSDC) fleet is the default; the "lf" experiment switches to the
# Linux Foundation fleet. META_LABEL_PREFIX is also the fallback on error.
META_LABEL_PREFIX = "mt-"
META_CANARY_LABEL_PREFIX = "c-mt-"
LF_LABEL_PREFIX = "lf-"
AMD_SANDBOX_EXPERIMENT = "amd-sandbox"
AMD_SANDBOX_LABEL_PREFIX = "amd-sandbox-"
class Experiment(NamedTuple):
rollout_perc: float = (
0 # Percentage of workflows to experiment on when user is not opted-in.
)
all_branches: bool = (
False # If True, the experiment is also enabled on the exception branches
)
default: bool = (
True # If True, the experiment is enabled by default for all queries
)
# Per-experiment workflow eligibility. Comma-separated github.workflow
# names; when non-empty, only listed workflows are eligible for the
# experiment and rollout_perc is applied within that set. The literal
# "ALL" (or empty) makes every workflow eligible. A "-" prefix excludes
# that workflow even when "ALL" is present (e.g. "ALL,-B200 Smoke Tests");
# exclusions take priority over inclusions. Applied after user opt-in/out.
workflows: str = ""
# Add more fields as needed
class RunnerPrefixResult(NamedTuple):
prefix: str
# Dedicated prefix for the amd-sandbox experiment, exposed via its own output
# (amd-sandbox-label-type) instead of being folded into ``prefix``.
amd_sandbox_prefix: str = ""
class Settings(NamedTuple):
"""
Settings for the experiments that can be opted into.
"""
experiments: dict[str, Experiment] = {}
class ColorFormatter(logging.Formatter):
"""Color codes the log messages based on the log level"""
COLORS = {
"WARNING": "\033[33m", # Yellow
"ERROR": "\033[31m", # Red
"CRITICAL": "\033[31m", # Red
"INFO": "\033[0m", # Reset
"DEBUG": "\033[0m", # Reset
}
def format(self, record: LogRecord) -> str:
log_color = self.COLORS.get(record.levelname, "\033[0m") # Default to reset
record.msg = f"{log_color}{record.msg}\033[0m"
return super().format(record)
handler = logging.StreamHandler()
handler.setFormatter(ColorFormatter(fmt="%(levelname)-8s: %(message)s"))
log = logging.getLogger(os.path.basename(__file__))
log.addHandler(handler)
log.setLevel(logging.INFO)
def set_github_output(key: str, value: str) -> None:
"""
Defines outputs of the github action that invokes this script
"""
if not GITHUB_OUTPUT:
# See https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/ for deprecation notice
log.warning(
"No env var found for GITHUB_OUTPUT, you must be running this code locally. Falling back to the deprecated print method."
)
print(f"::set-output name={key}::{value}")
return
with open(GITHUB_OUTPUT, "a") as f:
log.info(f"Setting output: {key}='{value}'")
f.write(f"{key}={value}\n")
def _str_comma_separated_to_set(value: str) -> frozenset[str]:
return frozenset(
filter(lambda itm: itm != "", map(str.strip, value.strip(" \n\t").split(",")))
)
def parse_args() -> Any:
parser = ArgumentParser("Get dynamic rollout settings")
parser.add_argument("--github-token", type=str, required=True, help="GitHub token")
parser.add_argument(
"--github-issue-repo",
type=str,
required=False,
default="pytorch/test-infra",
help="GitHub repo to get the issue",
)
parser.add_argument(
"--github-repo",
type=str,
required=True,
help="GitHub repo where CI is running",
)
parser.add_argument(
"--github-issue", type=int, required=True, help="GitHub issue number"
)
parser.add_argument(
"--github-actor", type=str, required=True, help="GitHub triggering_actor"
)
parser.add_argument(
"--github-issue-owner", type=str, required=True, help="GitHub issue owner"
)
parser.add_argument(
"--github-branch", type=str, required=True, help="Current GitHub branch or tag"
)
parser.add_argument(
"--github-ref-type",
type=str,
required=True,
help="Current GitHub ref type, branch or tag",
)
parser.add_argument(
"--eligible-experiments",
type=_str_comma_separated_to_set,
required=False,
default="",
help="comma separated list of experiments to check, if omitted all experiments marked with default=True are checked",
)
parser.add_argument(
"--opt-out-experiments",
type=_str_comma_separated_to_set,
required=False,
default="",
help=(
"comma separated list of experiments to opt-out of. If unset, no opt-outs will occur. "
"If the same experiment is listed both here and in '--eligible-experiments' opt-out will take priority."
),
)
parser.add_argument(
"--pr-number",
type=str,
required=False,
default="",
help="the optional PR number where this is run",
)
parser.add_argument(
"--workflow-name",
type=str,
required=False,
default="",
help="the name of the calling workflow (github.workflow)",
)
return parser.parse_args()
def get_gh_client(github_token: str) -> Github: # type: ignore[no-any-unimported]
auth = Auth.Token(github_token)
return Github(auth=auth)
def get_issue(gh: Github, repo: str, issue_num: int) -> Issue: # type: ignore[no-any-unimported]
repo = gh.get_repo(repo)
return repo.get_issue(number=issue_num)
def get_potential_pr_author(
github_token: str, repo: str, username: str, ref_type: str, ref_name: str
) -> str:
# If the trigger was a new tag added by a bot, this is a ciflow case
# Fetch the actual username from the original PR. The PR number is
# embedded in the tag name: ciflow/<name>/<pr-number>
gh = get_gh_client(github_token)
if username == "pytorch-bot[bot]" and ref_type == "tag":
split_tag = ref_name.split("/")
if (
len(split_tag) == 3
and split_tag[0] == "ciflow"
and split_tag[2].isnumeric()
):
pr_number = split_tag[2]
try:
repository = gh.get_repo(repo)
pull = repository.get_pull(number=int(pr_number))
except Exception as e:
raise Exception( # noqa: TRY002
f"issue with pull request {pr_number} from repo {repository}"
) from e
return pull.user.login # type: ignore[no-any-return]
# In all other cases, return the original input username
return username
def is_exception_branch(branch: str) -> bool:
"""
Branches that get opted out of experiments by default, until they're explicitly enabled.
"""
return branch.split("/", maxsplit=1)[0] in {
"main",
"nightly",
"release",
"landchecks",
}
def load_yaml(yaml_text: str) -> Any:
try:
data = yaml.safe_load(yaml_text)
return data
except yaml.YAMLError:
log.exception("Error loading YAML")
raise
def extract_settings_user_opt_in_from_text(rollout_state: str) -> tuple[str, str]:
"""
Extracts the text with settings, if any, and the opted in users from the rollout state.
If the issue body contains "---" then the text above that is the settings
and the text below is the list of opted in users.
If it doesn't contain "---" then the settings are empty and the rest is the users.
"""
rollout_state_parts = rollout_state.split("---")
if len(rollout_state_parts) >= 2:
return rollout_state_parts[0], rollout_state_parts[1]
else:
return "", rollout_state
class UserExperimentConfig(NamedTuple):
"""
Per-user experiment configuration parsed from the opt-in line.
"""
name: str
rollout_perc: float = 100 # default: always enabled when opted in
class UserOptins(dict[str, list[UserExperimentConfig]]):
"""
Dictionary of users with a list of experiment configs they have opted into
"""
def parse_workflow_list(workflows: str) -> set[str]:
"""
Parse the per-experiment ``workflows`` setting into a set of allowlisted
workflow names. Empty entries are ignored.
"""
return {entry.strip() for entry in workflows.split(",") if entry.strip()}
def parse_user_opt_in_from_text(user_optin_text: str) -> UserOptins:
"""
Parse the user opt-in text into a key value pair of username and the list of features they have opted into
Users are GitHub usernames with the @ prefix. Each user is also a comma-separated list of features/experiments to enable.
- Example line: "@User1,lf,split_build"
- A "#" prefix indicates the user is opted out of all experiments
"""
optins = UserOptins()
for user in user_optin_text.split("\n"):
user = user.strip("\r\n\t -")
if not user or not user.startswith("@"):
# Not a valid user. Skip
continue
if user:
usr_name = user.split(",")[0].strip("@")
configs = []
for exp_str in user.split(",")[1:]:
exp_str = exp_str.strip(" ")
if not exp_str:
continue
# Parse optional per-user rollout percentage (e.g. "lf:10")
# Opt-out entries (e.g. "-lf") never have a percentage
if ":" in exp_str and not exp_str.startswith("-"):
name, perc_str = exp_str.split(":", 1)
try:
perc = float(perc_str)
except ValueError:
log.warning(
f"Invalid rollout percentage for user {usr_name}, experiment {exp_str}. Defaulting to 100%."
)
perc = 100
if not (0 <= perc <= 100):
log.warning(
f"Rollout percentage {perc} for user {usr_name}, experiment {name} "
f"is out of range [0, 100]. Clamping."
)
perc = max(0.0, min(100.0, perc))
configs.append(UserExperimentConfig(name=name, rollout_perc=perc))
else:
configs.append(UserExperimentConfig(name=exp_str, rollout_perc=100))
optins[usr_name] = configs
return optins
def is_valid_experiment_name(experiment_name: str) -> bool:
"""
Check if the experiment name is valid.
A valid name:
- Contains only alphanumeric characters and the special characters "_" & "-"
- The special characters "_" & "-" shouldn't be the first or last characters
- Cannot contain spaces
"""
valid_char_regex = r"^[a-zA-Z0-9]([\w-]*[a-zA-Z0-9])?$"
valid = bool(re.match(valid_char_regex, experiment_name))
if valid:
return True
log.error(
f"Invalid experiment name: {experiment_name}. Experiment names should only contain alphanumeric characters, '_', and '-'. They cannot contain spaces, and the special characters '_' and '-' cannot be the first or last characters."
)
return False
def parse_settings_from_text(settings_text: str) -> Settings:
"""
Parse the experiments from the issue body into a list of ExperimentSettings
"""
try:
if settings_text:
# Strip backticks so settings can be in a code block on the GH issue
backtick = chr(96)
settings_text = settings_text.strip(f"\r\n\t{backtick} ")
settings = load_yaml(settings_text)
# For now we just load experiments. We can expand this if/when we add more settings
experiments = {}
for exp_name, exp_settings in settings.get(SETTING_EXPERIMENTS).items():
if not is_valid_experiment_name(exp_name):
# Exclude invalid experiments from the list. We log an error, but don't raise an exception so that other experiments can still be processed.
continue
valid_settings = {}
for setting in exp_settings:
if setting not in Experiment._fields:
log.warning(
f"Unexpected setting in experiment: {setting} = {exp_settings[setting]}"
)
else:
valid_settings[setting] = exp_settings[setting]
experiments[exp_name] = Experiment(**valid_settings)
return Settings(experiments)
except Exception:
log.exception("Failed to parse settings")
return Settings()
def parse_settings(rollout_state: str) -> Settings:
"""
Parse settings, if any, from the rollout state.
If the issue body contains "---" then the text above that is the settings
and the text below is the list of opted in users.
If it doesn't contain "---" then the settings are empty and the default values are used.
"""
settings_text, _ = extract_settings_user_opt_in_from_text(rollout_state)
return parse_settings_from_text(settings_text)
def parse_users(rollout_state: str) -> UserOptins:
"""
Parse users from the rollout state.
"""
_, users_text = extract_settings_user_opt_in_from_text(rollout_state)
return parse_user_opt_in_from_text(users_text)
def get_user_experiment_config(
user: str, user_optins: UserOptins, experiment_name: str
) -> UserExperimentConfig | None:
"""
Get a user's experiment config if they are opted in.
Returns None if the user is not opted into the experiment.
"""
for config in user_optins.get(user, []):
if config.name == experiment_name:
return config
return None
def is_user_opted_in(user: str, user_optins: UserOptins, experiment_name: str) -> bool:
"""
Check if a user is opted into an experiment
"""
return get_user_experiment_config(user, user_optins, experiment_name) is not None
def is_user_opted_out(user: str, user_optins: UserOptins, experiment_name: str) -> bool:
"""
Check if a user explicitly opted out of an experiment
"""
# if the experiment is prefixed with a "-", then it's an opt-out
experiment_optout = "-" + experiment_name
opted_out = any(
config.name == experiment_optout for config in user_optins.get(user, [])
)
if not opted_out:
return False
if is_user_opted_in(user, user_optins, experiment_name):
log.warning(
f"User {user} is opted into experiment {experiment_name}, but also opted out of it. Defaulting to opting out"
)
return True
def get_runner_prefix(
rollout_state: str,
workflow_requestors: Iterable[str],
branch: str,
eligible_experiments: frozenset[str] = frozenset(),
opt_out_experiments: frozenset[str] = frozenset(),
is_canary: bool = False,
workflow_name: str = "",
) -> RunnerPrefixResult:
settings = parse_settings(rollout_state)
user_optins = parse_users(rollout_state)
lf_enabled = False
amd_sandbox_prefix = ""
for experiment_name, experiment_settings in settings.experiments.items():
if not experiment_settings.all_branches and is_exception_branch(branch):
log.info(
f"Branch {branch} is an exception branch. Not enabling experiment {experiment_name}."
)
continue
if opt_out_experiments:
if experiment_name in opt_out_experiments:
opt_out_exp_list = ", ".join(opt_out_experiments)
log.info(
f"Skipping experiment '{experiment_name}', as this workflow has opted-out (opted out experiments are: {opt_out_exp_list})"
)
continue
if eligible_experiments:
if experiment_name not in eligible_experiments:
exp_list = ", ".join(eligible_experiments)
log.info(
f"Skipping experiment '{experiment_name}', as it is not in the eligible_experiments list: {exp_list}"
)
continue
elif not experiment_settings.default:
log.info(
f"Skipping experiment '{experiment_name}', as it is not a default experiment"
)
continue
# Is any workflow_requestor opted out to this experiment?
opted_out_users = [
requestor
for requestor in workflow_requestors
if is_user_opted_out(requestor, user_optins, experiment_name)
]
if opted_out_users:
log.info(
f"{', '.join(opted_out_users)} have opted out of experiment {experiment_name}."
)
continue
# Is any workflow_requestor opted in to this experiment?
opted_in_users = [
requestor
for requestor in workflow_requestors
if is_user_opted_in(requestor, user_optins, experiment_name)
]
enabled = False
if opted_in_users:
# Get the minimum per-user rollout percentage among opted-in requesters.
# This is conservative: if the PR author sets 10%, that intent is respected
# even if the triggering actor (e.g. pytorchmergebot) has 100%.
user_rollout_percs = [
get_user_experiment_config(u, user_optins, experiment_name).rollout_perc
for u in opted_in_users
]
min_perc = min(user_rollout_percs)
if min_perc >= 100:
log.info(
f"{', '.join(opted_in_users)} have opted into experiment {experiment_name}."
)
enabled = True
elif min_perc > 0:
if random.uniform(0, 100) <= min_perc:
log.info(
f"{', '.join(opted_in_users)} have opted into experiment {experiment_name} "
f"with {min_perc}% rollout. Enabling this run."
)
enabled = True
else:
log.info(
f"{', '.join(opted_in_users)} have opted into experiment {experiment_name} "
f"with {min_perc}% rollout. Not enabling this run."
)
else:
log.info(
f"{', '.join(opted_in_users)} have opted into experiment {experiment_name} "
f"with 0% rollout. Not enabling."
)
else:
# workflows: gates which workflows are eligible. rollout_perc is
# applied within that gate; non-listed workflows are 0%. The
# literal "ALL" (or empty) makes every workflow eligible. Entries
# prefixed with "-" are exclusions that take priority, so
# "ALL,-foo" enables every workflow except "foo".
workflow_list = parse_workflow_list(experiment_settings.workflows)
excluded = {e[1:] for e in workflow_list if e.startswith("-")}
included = {e for e in workflow_list if not e.startswith("-")}
eligible = (
not included
or WORKFLOW_ALLOWLIST_ALL in included
or (workflow_name and workflow_name in included)
) and workflow_name not in excluded
if not eligible:
log.info(
f"Workflow '{workflow_name}' is not eligible for experiment "
f"{experiment_name}. Skipping."
)
continue
if experiment_settings.rollout_perc:
if random.uniform(0, 100) <= experiment_settings.rollout_perc:
log.info(
f"Based on rollout percentage of {experiment_settings.rollout_perc}%, enabling experiment {experiment_name}."
)
enabled = True
if enabled:
if experiment_name == AMD_SANDBOX_EXPERIMENT:
# The amd-sandbox experiment is exposed through its own
# amd-sandbox-label-type output rather than being mixed into the
# shared label-type prefix, so it can be applied per-job.
amd_sandbox_prefix = AMD_SANDBOX_LABEL_PREFIX
log.info(
"amd-sandbox experiment enabled. Exposing 'amd-sandbox-' prefix via the amd-sandbox-label-type output."
)
elif experiment_name == LF_FLEET_EXPERIMENT:
lf_enabled = True
log.info("lf experiment enabled. Using the Linux Foundation fleet.")
else:
log.info(
f"Experiment '{experiment_name}' enabled but no longer affects "
"the runner label prefix; ignoring."
)
# Fleet selection: the Meta (OSDC) fleet is the default; the lf experiment
# switches to the Linux Foundation fleet.
if lf_enabled:
prefix = LF_LABEL_PREFIX
else:
prefix = META_CANARY_LABEL_PREFIX if is_canary else META_LABEL_PREFIX
return RunnerPrefixResult(prefix=prefix, amd_sandbox_prefix=amd_sandbox_prefix)
def get_rollout_state_from_issue(github_token: str, repo: str, issue_num: int) -> str:
"""
Gets the first comment of the issue, which contains the desired rollout state.
The default issue we use - https://github.com/pytorch/test-infra/issues/5132
"""
gh = get_gh_client(github_token)
issue = get_issue(gh, repo, issue_num)
return str(issue.get_comments()[0].body.strip("\n\t "))
def download_json(url: str, headers: dict[str, str], num_retries: int = 3) -> Any:
for _ in range(num_retries):
try:
req = Request(url=url, headers=headers)
content = urlopen(req, timeout=5).read().decode("utf-8")
return json.loads(content)
except Exception as e:
log.warning(f"Could not download {url}: {e}")
log.warning(f"All {num_retries} retries exhausted, downloading {url} failed")
return {}
@cache
def get_pr_info(github_repo: str, github_token: str, pr_number: int) -> dict[str, Any]:
"""
Dynamically get PR information
"""
github_api = f"https://api.github.com/repos/{github_repo}"
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"token {github_token}",
}
json_response: dict[str, Any] = download_json(
url=f"{github_api}/issues/{pr_number}",
headers=headers,
)
if not json_response:
log.warning(f"Failed to get the labels for #{pr_number}")
return {}
return json_response
def get_labels(github_repo: str, github_token: str, pr_number: int) -> set[str]:
"""
Dynamically get the latest list of labels from the pull request
"""
pr_info = get_pr_info(github_repo, github_token, pr_number)
return {
label.get("name") for label in pr_info.get("labels", []) if label.get("name")
}
def main() -> None:
args = parse_args()
runner_label_prefix = META_LABEL_PREFIX
amd_sandbox_label_prefix = ""
# no-runner-experiments means "use Meta, not LF": opt out of the lf
# experiment, so the run stays on the default Meta fleet.
opt_out_experiments = args.opt_out_experiments
if args.pr_number:
labels = get_labels(args.github_repo, args.github_token, int(args.pr_number))
if OPT_OUT_LABEL in labels:
log.info(
f"#{args.pr_number} has {OPT_OUT_LABEL}; opting out of the "
f"'{LF_FLEET_EXPERIMENT}' experiment"
)
opt_out_experiments = opt_out_experiments | {LF_FLEET_EXPERIMENT}
if args.workflow_name:
log.info(f"Workflow name: '{args.workflow_name}'")
try:
rollout_state = get_rollout_state_from_issue(
args.github_token, args.github_issue_repo, args.github_issue
)
username = get_potential_pr_author(
args.github_token,
args.github_repo,
args.github_actor,
args.github_ref_type,
args.github_branch,
)
is_canary = args.github_repo == "pytorch/pytorch-canary"
result = get_runner_prefix(
rollout_state,
(args.github_issue_owner, username),
args.github_branch,
args.eligible_experiments,
opt_out_experiments,
is_canary,
workflow_name=args.workflow_name,
)
runner_label_prefix = result.prefix
amd_sandbox_label_prefix = result.amd_sandbox_prefix
except Exception as e:
log.error(
f"Failed to get issue. Defaulting to Meta runners and no experiments. Exception: {e}"
)
set_github_output(GH_OUTPUT_KEY_LABEL_TYPE, runner_label_prefix)
set_github_output(GH_OUTPUT_KEY_AMD_SANDBOX_LABEL_TYPE, amd_sandbox_label_prefix)
if __name__ == "__main__":
main()