-
Notifications
You must be signed in to change notification settings - Fork 613
Swarming: Adds CountTasks endpoint & Refactors swarming Prpc request #5277
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
IvanBM18
wants to merge
13
commits into
master
Choose a base branch
from
feature/swarming/count_task_requests
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+341
−171
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
fc94459
Add TasksCountRequest and TasksCount to swarming.proto
IvanBM18 56be2f4
Implement CountTasks and refactor Swarming API
IvanBM18 d78a8eb
Removes push_swarming_task method & reuses get_swarming_config at the…
IvanBM18 0ede2ed
Adds api as a SwarmingService property
IvanBM18 57886fc
Fixes Broken UT
IvanBM18 5a430c3
Adds endpoint constants
IvanBM18 6b5715d
Fixes linter issues
IvanBM18 5299ee9
Merge branch 'master' into feature/swarming/count_task_requests
IvanBM18 e55457d
Apply suggestion from @letitz
IvanBM18 0bf3497
Propagates errors from api to service
IvanBM18 79cd11a
Removes unnecesary code & uses test config in UT
IvanBM18 495fe97
Merge branch 'master' into feature/swarming/count_task_requests
IvanBM18 b5102a6
Update copyright year from 2023 to 2026
IvanBM18 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # 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. | ||
| """Swarming pRPC API client.""" | ||
|
|
||
| from typing import Optional | ||
|
|
||
| from google.auth import exceptions as auth_exceptions | ||
| from google.protobuf import json_format | ||
|
|
||
| from clusterfuzz._internal.base import utils | ||
| from clusterfuzz._internal.config.local_config import SwarmingConfig | ||
| from clusterfuzz._internal.google_cloud_utils import credentials | ||
| from clusterfuzz._internal.metrics import logs | ||
| from clusterfuzz._internal.protos import swarming_pb2 | ||
| from clusterfuzz._internal.swarming import get_swarming_config | ||
|
|
||
| _SWARMING_SCOPES = [ | ||
| 'https://www.googleapis.com/auth/cloud-platform', | ||
| 'https://www.googleapis.com/auth/userinfo.email' | ||
| ] | ||
|
|
||
| _COUNT_TASKS_ENDPOINT = 'swarming.v2.Tasks/CountTasks' | ||
| _NEW_TASK_ENDPOINT = 'swarming.v2.Tasks/NewTask' | ||
|
|
||
|
|
||
| class SwarmingApi: | ||
| """Client for Swarming pRPC API.""" | ||
|
|
||
| _config: SwarmingConfig | ||
| _base_url: str = "" | ||
|
|
||
| def __init__(self, config: SwarmingConfig): | ||
| self._config = config | ||
| self._base_url = f"https://{self._config.get('swarming_server')}/prpc/" | ||
|
|
||
| @staticmethod | ||
| def create() -> Optional['SwarmingApi']: | ||
| """Creates a SwarmingApi instance if config is available. | ||
|
|
||
| Returns: | ||
| A SwarmingApi instance if config is available, None otherwise. | ||
| """ | ||
| config = get_swarming_config() | ||
| if config is None: | ||
| return None | ||
|
|
||
| return SwarmingApi(config) | ||
|
|
||
| def _get_token(self) -> str: | ||
| """Gets a valid token for the Swarming API. Returns "" if it fails.""" | ||
| try: | ||
| creds = credentials.get_scoped_service_account_credentials( | ||
| _SWARMING_SCOPES) | ||
| if not creds: | ||
| logs.error('[Swarming] Failed to get credentials. None found.') | ||
| return "" | ||
|
|
||
| return creds.token | ||
| except (auth_exceptions.DefaultCredentialsError, | ||
| auth_exceptions.RefreshError, auth_exceptions.TransportError) as e: | ||
| logs.error(f'[Swarming] Failed to get token with: {e}.') | ||
| return "" | ||
|
|
||
| def _get_headers(self) -> dict[str, str]: | ||
| """Checks config and returns headers for pRPC request. | ||
|
|
||
| Returns: | ||
| A dict containing headers. | ||
| """ | ||
| token = self._get_token() | ||
|
|
||
| return { | ||
| 'Accept': 'application/json', | ||
| 'Content-Type': 'application/json', | ||
| 'Authorization': f'Bearer {token}' | ||
| } | ||
|
|
||
| def _make_request(self, endpoint: str, body: str) -> str | None: | ||
| """Makes a pRPC request to the Swarming API. | ||
|
|
||
| Args: | ||
| endpoint: The pRPC endpoint (e.g. "swarming.v2.Tasks/NewTask"). | ||
| body: The JSON body of the request. | ||
|
|
||
| Returns: | ||
| The raw JSON response string from the server, or None if the response is | ||
| empty. | ||
|
|
||
| Raises: | ||
| requests.exceptions.HTTPError: If the request fails with a 4xx or 5xx | ||
| status code. | ||
| """ | ||
| headers = self._get_headers() | ||
|
|
||
| url = f'{self._base_url}{endpoint}' | ||
| logs.info( | ||
| f"[Swarming] Making request to {url}", | ||
| url=self._base_url, | ||
| endpoint=endpoint, | ||
| body=body, | ||
| headers=headers) | ||
| response = utils.post_url(url=url, data=body, headers=headers) | ||
| if not response: | ||
| logs.error(f"[Swarming] Failed to make request to {url}. Empty response") | ||
| return None | ||
| return response | ||
|
|
||
| def push_task(self, task_request: swarming_pb2.NewTaskRequest) -> str | None: # pylint: disable=no-member | ||
| """Schedules a task on swarming. | ||
|
|
||
| Args: | ||
| task_request: The NewTaskRequest proto message. | ||
|
|
||
| Returns: | ||
| The raw JSON response string from the server, or None if the response is | ||
| empty. | ||
|
|
||
| Raises: | ||
| requests.exceptions.HTTPError: If the request fails with a 4xx or 5xx | ||
| status code. | ||
| """ | ||
| message_body = json_format.MessageToJson(task_request) | ||
|
|
||
| response = self._make_request(_NEW_TASK_ENDPOINT, message_body) | ||
| return response | ||
|
|
||
| def count_tasks(self, | ||
|
Xeicker marked this conversation as resolved.
|
||
| count_request: swarming_pb2.TasksCountRequest) -> str | None: # pylint: disable=no-member | ||
| """Counts tasks on swarming. | ||
|
|
||
| Args: | ||
| count_request: The TasksCountRequest proto message. | ||
|
|
||
| Returns: | ||
| The raw JSON response string from the server, or None if the response is | ||
| empty. | ||
|
|
||
| Raises: | ||
| requests.exceptions.HTTPError: If the request fails with a 4xx or 5xx | ||
| status code. | ||
| """ | ||
| message_body = json_format.MessageToJson(count_request) | ||
|
|
||
| response = self._make_request(_COUNT_TASKS_ENDPOINT, message_body) | ||
| return response | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIUC this means we'll make requests with no tokens if we fail to get a token, which is bound to fail? ISTM we should bail out and not make a request if we cannot get an auth token for it.
I would either expose to callers that
SwarmingApimethods might raise eitherGoogleAuthErrororRequestException, or wrap those in a new exception type here:SwarmingErrorand let the caller deal with that.Edit: I see your comment on the test, that this will show up as 401 errors. I still find it a bit surprising to ask the system to do something we know will fail, but I must admit it works. I'll let @javanlacerda decide how he feels about it.