Buckets:
xuan-luo/kvpath-optimization / KDA-optimization /env /third_party /Megatron-LM /.github /scripts /oncall_manager.py
| # Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from datetime import datetime, timedelta, timezone | |
| import requests | |
| from github_slack_utils import SlackApiError, get_slack_client, get_slack_user_id, get_user_email | |
| # Constants | |
| GITHUB_API_URL = "https://api.github.com" | |
| SCHEDULE_FILE = ".github/oncall_schedule.json" | |
| ROTATION_TEAM_SLUG = "mcore-oncall-rotation" | |
| ACTIVE_ONCALL_TEAM_SLUG = "mcore-oncall" | |
| SLACK_USERGROUP_HANDLE = "mcore-oncall" | |
| COMMUNITY_REQUEST_LABEL = "community-request" | |
| SERVICE_ACCOUNT_USERNAME = "svcnvidia-nemo-ci" | |
| TARGET_WEEKS = 12 | |
| def get_headers(): | |
| token = os.environ.get("GH_TOKEN") | |
| if not token: | |
| # Fallback to GITHUB_TOKEN if GH_TOKEN not set | |
| token = os.environ.get("GITHUB_TOKEN") | |
| if not token: | |
| print("Error: GH_TOKEN or GITHUB_TOKEN not set") | |
| sys.exit(1) | |
| token = token.strip() | |
| if not token or any(char.isspace() for char in token): | |
| print("Error: GH_TOKEN or GITHUB_TOKEN is invalid") | |
| sys.exit(1) | |
| return {"Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json"} | |
| def get_repo_info(): | |
| """Returns (owner, repo) from GITHUB_REPOSITORY env var.""" | |
| repo_env = os.environ.get("GITHUB_REPOSITORY") | |
| if not repo_env: | |
| print("Error: GITHUB_REPOSITORY environment variable not set") | |
| sys.exit(1) | |
| parts = repo_env.split("/") | |
| return parts[0], parts[1] | |
| def get_team_members(org, team_slug): | |
| """Fetches members of the GitHub team.""" | |
| url = f"{GITHUB_API_URL}/orgs/{org}/teams/{team_slug}/members" | |
| headers = get_headers() | |
| members = set() | |
| page = 1 | |
| while True: | |
| resp = requests.get(f"{url}?per_page=100&page={page}", headers=headers) | |
| if resp.status_code != 200: | |
| print(f"Error fetching team members: {resp.status_code} {resp.text}") | |
| sys.exit(1) | |
| data = resp.json() | |
| if not data: | |
| break | |
| members.update([m['login'] for m in data]) | |
| if len(data) < 100: | |
| break | |
| page += 1 | |
| return members | |
| def get_slack_usergroup_id(slack_client, handle): | |
| """Get Slack usergroup ID from handle.""" | |
| if not slack_client: | |
| return None | |
| try: | |
| response = slack_client.usergroups_list(include_users=True) | |
| for usergroup in response.get("usergroups", []): | |
| if usergroup.get("handle") == handle: | |
| return usergroup.get("id"), usergroup.get("users", []) | |
| print(f"Warning: Slack usergroup '{handle}' not found") | |
| return None, [] | |
| except SlackApiError as e: | |
| print(f"Warning: Could not list Slack usergroups: {e.response['error']}") | |
| return None, [] | |
| def update_slack_usergroup(new_oncall_username, old_members_usernames): | |
| """ | |
| Updates the Slack usergroup to contain only the new oncall user. | |
| Adds new oncall first, then removes old members (usergroups need at least one member). | |
| """ | |
| slack_client = get_slack_client() | |
| if not slack_client: | |
| print("Slack token not configured, skipping Slack usergroup update") | |
| return | |
| # Get the new oncall's email and Slack user ID | |
| new_email = get_user_email(new_oncall_username) | |
| new_slack_id = get_slack_user_id(slack_client, new_email) | |
| if not new_slack_id: | |
| print( | |
| f"Could not find Slack user ID for {new_oncall_username} ({new_email}), skipping Slack update" | |
| ) | |
| return | |
| # Get the usergroup ID and current members | |
| usergroup_id, current_slack_members = get_slack_usergroup_id( | |
| slack_client, SLACK_USERGROUP_HANDLE | |
| ) | |
| if not usergroup_id: | |
| print(f"Could not find Slack usergroup '{SLACK_USERGROUP_HANDLE}', skipping Slack update") | |
| return | |
| try: | |
| # Step 1: Add new oncall first (include current members to avoid removing anyone yet) | |
| # This ensures usergroup always has at least one member | |
| if new_slack_id not in current_slack_members: | |
| updated_members = list(set(current_slack_members + [new_slack_id])) | |
| slack_client.usergroups_users_update(usergroup=usergroup_id, users=updated_members) | |
| print(f"Added {new_oncall_username} to Slack usergroup '{SLACK_USERGROUP_HANDLE}'") | |
| # Step 2: Now set the usergroup to contain only the new oncall | |
| slack_client.usergroups_users_update(usergroup=usergroup_id, users=[new_slack_id]) | |
| print( | |
| f"Updated Slack usergroup '{SLACK_USERGROUP_HANDLE}' to contain only {new_oncall_username}" | |
| ) | |
| except SlackApiError as e: | |
| print(f"Failed to update Slack usergroup: {e.response['error']}") | |
| def load_schedule(): | |
| if not os.path.exists(SCHEDULE_FILE): | |
| return [] | |
| try: | |
| with open(SCHEDULE_FILE, 'r') as f: | |
| data = json.load(f) | |
| # Normalize to list of dicts if it's a list of strings | |
| schedule = [] | |
| for item in data: | |
| if isinstance(item, str): | |
| schedule.append({"user": item, "date": "YYYY-MM-DD"}) | |
| else: | |
| schedule.append(item) | |
| return schedule | |
| except (json.JSONDecodeError, FileNotFoundError): | |
| return [] | |
| def save_schedule(schedule): | |
| with open(SCHEDULE_FILE, 'w') as f: | |
| json.dump(schedule, f, indent=4) | |
| f.write('\n') # trailing newline | |
| def get_rotation_order(repo_owner): | |
| """Returns rotation team members in alphabetical order.""" | |
| members = get_team_members(repo_owner, ROTATION_TEAM_SLUG) | |
| members.discard(SERVICE_ACCOUNT_USERNAME) | |
| return sorted(members, key=str.casefold) | |
| def validate_schedule_users_in_rotation_team(schedule, rotation_order): | |
| """Validates scheduled users are members of the rotation team.""" | |
| schedule_users = {entry.get('user') for entry in schedule if entry.get('user')} | |
| if not schedule_users: | |
| print("Warning: No users found in schedule. Cannot validate rotation team membership.") | |
| return | |
| rotation_team_members = set(rotation_order) | |
| if not rotation_team_members: | |
| print(f"Error: No members found in {ROTATION_TEAM_SLUG}.") | |
| sys.exit(1) | |
| missing_users = sorted(schedule_users - rotation_team_members, key=str.casefold) | |
| if missing_users: | |
| print( | |
| f"Error: Scheduled oncall user(s) are not members of " | |
| f"{ROTATION_TEAM_SLUG}: {', '.join(missing_users)}" | |
| ) | |
| sys.exit(1) | |
| print(f"Validated {len(schedule_users)} scheduled user(s) in {ROTATION_TEAM_SLUG}.") | |
| def update_active_oncall_team(org, new_oncall): | |
| """Updates the active oncall team to contain only the new oncall user.""" | |
| # 1. Get current members of the active team | |
| current_members = get_team_members(org, ACTIVE_ONCALL_TEAM_SLUG) | |
| # 2. Add the new oncall if not present | |
| if new_oncall not in current_members: | |
| url = ( | |
| f"{GITHUB_API_URL}/orgs/{org}/teams/{ACTIVE_ONCALL_TEAM_SLUG}/memberships/{new_oncall}" | |
| ) | |
| resp = requests.put(url, headers=get_headers()) | |
| if resp.status_code == 200: | |
| print(f"Added {new_oncall} to {ACTIVE_ONCALL_TEAM_SLUG}") | |
| else: | |
| print( | |
| f"Failed to add {new_oncall} to {ACTIVE_ONCALL_TEAM_SLUG}: {resp.status_code} {resp.text}" | |
| ) | |
| # 3. Remove everyone else | |
| old_members = [] | |
| for member in current_members: | |
| if member not in [new_oncall, 'svcnvidia-nemo-ci']: | |
| old_members.append(member) | |
| url = ( | |
| f"{GITHUB_API_URL}/orgs/{org}/teams/{ACTIVE_ONCALL_TEAM_SLUG}/memberships/{member}" | |
| ) | |
| resp = requests.delete(url, headers=get_headers()) | |
| if resp.status_code == 204: | |
| print(f"Removed {member} from {ACTIVE_ONCALL_TEAM_SLUG}") | |
| else: | |
| print( | |
| f"Failed to remove {member} from {ACTIVE_ONCALL_TEAM_SLUG}: {resp.status_code} {resp.text}" | |
| ) | |
| # 4. Update Slack usergroup (add new oncall first, then remove old members) | |
| update_slack_usergroup(new_oncall, old_members) | |
| def rotate_schedule(repo_owner, dry_run=False): | |
| schedule = load_schedule() | |
| rotation_order = get_rotation_order(repo_owner) | |
| validate_schedule_users_in_rotation_team(schedule, rotation_order) | |
| print(f"Current schedule length: {len(schedule)}") | |
| # 1. Rotate (Remove past week) | |
| # Only if schedule is not empty. | |
| if schedule: | |
| # Check date of first entry | |
| first_entry = schedule[0] | |
| try: | |
| # We assume the date is the *start* of the oncall shift (Wednesday). | |
| # The shift ends 7 days later. | |
| start_date = datetime.strptime(first_entry['date'], "%Y-%m-%d").date() | |
| end_date = start_date + timedelta(days=7) | |
| today = datetime.now(timezone.utc).date() | |
| # If today is >= end_date, the shift is over. | |
| # (e.g. Started last Wed, ends today Wed. If today is Wed, we rotate) | |
| if today >= end_date: | |
| removed = schedule.pop(0) | |
| print(f"Rotated out: {removed} (Ended {end_date})") | |
| else: | |
| print( | |
| f"First entry {first_entry} has not ended yet (Ends {end_date}). Not removing." | |
| ) | |
| except ValueError: | |
| # Fallback if date is invalid, rotate anyway | |
| removed = schedule.pop(0) | |
| print(f"Rotated out (invalid date): {removed}") | |
| else: | |
| print("Schedule empty, nothing to rotate.") | |
| # 2. Replenish | |
| ensure_schedule_filled(schedule, rotation_order) | |
| # 3. Update active oncall team | |
| if schedule: | |
| current_oncall = schedule[0]['user'] | |
| print(f"New active oncall: {current_oncall}") | |
| if not dry_run: | |
| update_active_oncall_team(repo_owner, current_oncall) | |
| else: | |
| print( | |
| f"Dry run: Would update {ACTIVE_ONCALL_TEAM_SLUG} to contain only {current_oncall}" | |
| ) | |
| if not dry_run: | |
| save_schedule(schedule) | |
| print("Schedule updated and saved.") | |
| else: | |
| print("Dry run: Schedule not saved.") | |
| print(json.dumps(schedule, indent=4)) | |
| def get_last_wednesday(): | |
| today = datetime.now(timezone.utc).date() | |
| # Monday=0, Wednesday=2 | |
| offset = (today.weekday() - 2) % 7 | |
| return today - timedelta(days=offset) | |
| def ensure_schedule_filled(schedule, rotation_order=None): | |
| """Appends users to schedule until it reaches TARGET_WEEKS.""" | |
| if not rotation_order: | |
| print(f"Warning: No users found in {ROTATION_TEAM_SLUG}. Cannot fill schedule.") | |
| return | |
| while len(schedule) < TARGET_WEEKS: | |
| # Determine start date for the new entry | |
| if not schedule: | |
| # Start with the most recent Wednesday if list is empty | |
| next_date = get_last_wednesday() | |
| # Start with the first user in the rotation team order if list is empty | |
| next_user = rotation_order[0] | |
| else: | |
| last_entry = schedule[-1] | |
| last_user = last_entry['user'] | |
| # Parse last date and add 7 days | |
| try: | |
| last_date = datetime.strptime(last_entry['date'], "%Y-%m-%d").date() | |
| next_date = last_date + timedelta(days=7) | |
| except ValueError: | |
| # Fallback if date is invalid/placeholder | |
| next_date = get_last_wednesday() + timedelta(days=7 * len(schedule)) | |
| try: | |
| # Find index of last scheduled user in the rotation team order | |
| if last_user in rotation_order: | |
| last_idx = rotation_order.index(last_user) | |
| next_idx = (last_idx + 1) % len(rotation_order) | |
| next_user = rotation_order[next_idx] | |
| else: | |
| # Last user not in schedule order, just pick first user | |
| next_user = rotation_order[0] | |
| except ValueError: | |
| next_user = rotation_order[0] | |
| new_entry = {"user": next_user, "date": next_date.strftime("%Y-%m-%d")} | |
| schedule.append(new_entry) | |
| print(f"Appended: {new_entry}") | |
| def assign_reviewer(pr_number): | |
| """Assigns mcore-oncall if no reviewers are set or community-request is applied.""" | |
| owner, repo = get_repo_info() | |
| pr_url = f"{GITHUB_API_URL}/repos/{owner}/{repo}/pulls/{pr_number}" | |
| pr_resp = requests.get(pr_url, headers=get_headers()) | |
| if pr_resp.status_code != 200: | |
| print(f"Failed to fetch PR: {pr_resp.status_code} {pr_resp.text}") | |
| sys.exit(1) | |
| pr_data = pr_resp.json() | |
| requested_reviewers = pr_data.get("requested_reviewers", []) | |
| requested_teams = pr_data.get("requested_teams", []) | |
| labels = {label.get("name") for label in pr_data.get("labels", [])} | |
| requested_team_slugs = {team.get("slug") for team in requested_teams} | |
| has_community_request_label = COMMUNITY_REQUEST_LABEL in labels | |
| if ACTIVE_ONCALL_TEAM_SLUG in requested_team_slugs: | |
| print( | |
| f"Skipping reviewer request: team NVIDIA/{ACTIVE_ONCALL_TEAM_SLUG} " | |
| "is already requested" | |
| ) | |
| return | |
| if not has_community_request_label and (requested_reviewers or requested_teams): | |
| print( | |
| "Skipping reviewer request: PR already has " | |
| f"{len(requested_reviewers)} user reviewer(s) and " | |
| f"{len(requested_teams)} team reviewer(s)" | |
| ) | |
| return | |
| url = f"{GITHUB_API_URL}/repos/{owner}/{repo}/pulls/{pr_number}/requested_reviewers" | |
| # Assign the oncall team as reviewer | |
| data = {"team_reviewers": [ACTIVE_ONCALL_TEAM_SLUG]} | |
| resp = requests.post(url, headers=get_headers(), json=data) | |
| if resp.status_code in [201, 200]: | |
| print(f"Successfully requested review from team NVIDIA/{ACTIVE_ONCALL_TEAM_SLUG}") | |
| else: | |
| print(f"Failed to request review: {resp.status_code} {resp.text}") | |
| sys.exit(1) | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Manage Oncall Schedule") | |
| subparsers = parser.add_subparsers(dest="command", required=True) | |
| # Rotate command | |
| parser_rotate = subparsers.add_parser( | |
| "rotate", help="Rotate the schedule (remove first, append new)" | |
| ) | |
| parser_rotate.add_argument("--dry-run", action="store_true", help="Do not save changes") | |
| # Fill command (just fill up to 12 without rotating - useful for init) | |
| parser_fill = subparsers.add_parser( | |
| "fill", help="Fill the schedule to 12 weeks without rotating" | |
| ) | |
| # Assign command | |
| parser_assign = subparsers.add_parser("assign", help="Assign current oncall to PR") | |
| parser_assign.add_argument("--pr", type=int, required=True, help="PR number") | |
| args = parser.parse_args() | |
| owner, _ = get_repo_info() | |
| if args.command == "rotate": | |
| rotate_schedule(owner, dry_run=args.dry_run) | |
| elif args.command == "fill": | |
| schedule = load_schedule() | |
| rotation_order = get_rotation_order(owner) | |
| validate_schedule_users_in_rotation_team(schedule, rotation_order) | |
| ensure_schedule_filled(schedule, rotation_order) | |
| save_schedule(schedule) | |
| print("Schedule filled and saved.") | |
| elif args.command == "assign": | |
| assign_reviewer(args.pr) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 15.9 kB
- Xet hash:
- b3d3769fee6eb614cdba038dbbd7ace0b5f6d676aa205db31441b910f76dc43f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.