-
-
Notifications
You must be signed in to change notification settings - Fork 316
feat: add SDK telemetry into emissions tracker #1200
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
davidberenstein1957
wants to merge
1
commit into
master
Choose a base branch
from
feat/add-telemetry
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.
Open
Changes from all commits
Commits
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,11 +3,14 @@ | |
| from uuid import UUID | ||
|
|
||
| from dependency_injector.wiring import Provide, inject | ||
| from fastapi import APIRouter, Depends | ||
| from fastapi import APIRouter, Depends, Header | ||
| from starlette import status | ||
|
|
||
| from carbonserver.api.schemas import AccessLevel | ||
| from carbonserver.api.schemas_telemetry import TelemetryCreate | ||
| from carbonserver.api.services.project_token_service import ProjectTokenService | ||
| from carbonserver.api.services.telemetry_service import TelemetryService | ||
| from carbonserver.config import settings | ||
| from carbonserver.container import ServerContainer | ||
|
|
||
| TELEMETRY_ROUTER_TAGS = ["Telemetry"] | ||
|
|
@@ -27,5 +30,14 @@ def add_telemetry( | |
| telemetry_service: TelemetryService = Depends( | ||
| Provide[ServerContainer.telemetry_service] | ||
| ), | ||
| project_token_service: ProjectTokenService = Depends( | ||
| Provide[ServerContainer.project_token_service] | ||
| ), | ||
| x_api_token: str = Header(None), | ||
| ) -> UUID: | ||
| project_token_service.project_token_has_access( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you are not doing anything with the response here, it should be |
||
| AccessLevel.WRITE.value, | ||
| experiment_id=settings.telemetry_experiment_id, | ||
| project_token=x_api_token, | ||
| ) | ||
| return telemetry_service.add_telemetry(telemetry) | ||
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
164 changes: 164 additions & 0 deletions
164
carbonserver/tests/api/integration/test_telemetry_local_api.py
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,164 @@ | ||
| """Integration tests for telemetry against a running local carbonserver API.""" | ||
|
|
||
| import os | ||
| import sys | ||
| import uuid | ||
| from datetime import datetime, timezone | ||
| from pathlib import Path | ||
| from types import SimpleNamespace | ||
|
|
||
| import pytest | ||
| import requests | ||
|
|
||
| REPO_ROOT = Path(__file__).resolve().parents[4] | ||
| sys.path.insert(0, str(REPO_ROOT)) | ||
|
|
||
| from codecarbon.core.telemetry.client import ( # noqa: E402 | ||
| post_private, | ||
| post_public_summary, | ||
| ) | ||
| from codecarbon.core.telemetry.collect import build_payload # noqa: E402 | ||
| from codecarbon.core.telemetry.schemas import TelemetryLevel # noqa: E402 | ||
| from codecarbon.core.telemetry.settings import ( # noqa: E402 | ||
| DEFAULT_TELEMETRY_EXPERIMENT_ID, | ||
| TelemetrySettings, | ||
| ) | ||
| from codecarbon.output_methods.emissions_data import EmissionsData # noqa: E402 | ||
|
|
||
| URL = os.getenv("CODECARBON_API_URL") | ||
| if URL is None: | ||
| pytest.exit("CODECARBON_API_URL is not defined (e.g. http://localhost:8008)") | ||
|
|
||
| API_KEY = os.getenv("CODECARBON_TELEMETRY_API_KEY") | ||
| if not API_KEY: | ||
| pytest.exit("CODECARBON_TELEMETRY_API_KEY is not defined") | ||
|
|
||
|
|
||
| def _api_url(path: str) -> str: | ||
| base = URL.rstrip("/") | ||
| if not base.endswith("/api"): | ||
| base = f"{base}/api" | ||
| return f"{base}{path}" | ||
|
|
||
|
|
||
| def _local_settings() -> TelemetrySettings: | ||
| return TelemetrySettings.resolve( | ||
| external_conf={ | ||
| "telemetry_level": "extensive", | ||
| "telemetry_api_url": URL.rstrip("/"), | ||
| "telemetry_api_key": API_KEY, | ||
| "telemetry_experiment_id": DEFAULT_TELEMETRY_EXPERIMENT_ID, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _sample_emissions() -> EmissionsData: | ||
| return EmissionsData( | ||
| timestamp="2026-01-01T00:00:00", | ||
| project_name="telemetry-local", | ||
| run_id="local-run", | ||
| experiment_id=DEFAULT_TELEMETRY_EXPERIMENT_ID, | ||
| duration=10.0, | ||
| emissions=0.001, | ||
| emissions_rate=0.0001, | ||
| cpu_power=0.0, | ||
| gpu_power=0.0, | ||
| ram_power=0.0, | ||
| cpu_energy=0.0, | ||
| gpu_energy=0.0, | ||
| ram_energy=0.0, | ||
| energy_consumed=0.01, | ||
| water_consumed=0.0, | ||
| country_name="France", | ||
| country_iso_code="FRA", | ||
| region="idf", | ||
| cloud_provider="", | ||
| cloud_region="", | ||
| os="Linux", | ||
| python_version="3.12", | ||
| codecarbon_version="3.2.8", | ||
| cpu_count=4, | ||
| cpu_model="test-cpu", | ||
| gpu_count=0, | ||
| gpu_model="", | ||
| longitude=0.0, | ||
| latitude=0.0, | ||
| ram_total_size=16.0, | ||
| tracking_mode="process", | ||
| ) | ||
|
|
||
|
|
||
| def test_local_api_is_up(): | ||
| response = requests.get(URL.rstrip("/") + "/", timeout=5) | ||
| assert response.status_code == 200 | ||
| assert response.json()["status"] == "OK" | ||
|
|
||
|
|
||
| def test_local_telemetry_post_accepts_sdk_payload(): | ||
| settings = _local_settings() | ||
| tracker = SimpleNamespace( | ||
| _conf={ | ||
| "os": "Linux-5.10.0-x86_64", | ||
| "codecarbon_version": "3.2.8", | ||
| "cpu_count": 4, | ||
| "python_version": "3.12", | ||
| "tracking_mode": "process", | ||
| }, | ||
| ) | ||
| payload = build_payload(tracker, _sample_emissions(), level=TelemetryLevel.minimal) | ||
| assert post_private(settings, payload) is True | ||
|
|
||
|
|
||
| def test_local_extensive_run_and_emission_flow(): | ||
| settings = _local_settings() | ||
| run_payload = { | ||
| "timestamp": datetime.now(timezone.utc).isoformat(), | ||
| "experiment_id": settings.experiment_id, | ||
| "os": "Linux", | ||
| "python_version": "3.12", | ||
| "codecarbon_version": "3.2.8", | ||
| "cpu_count": 4, | ||
| "tracking_mode": "process", | ||
| } | ||
| run_response = requests.post( | ||
| _api_url("/runs"), | ||
| json=run_payload, | ||
| headers={"x-api-token": settings.api_key}, | ||
| timeout=10, | ||
| ) | ||
| assert run_response.status_code == 201, run_response.text | ||
| run_id = run_response.json()["id"] | ||
|
|
||
| emission_payload = { | ||
| "timestamp": datetime.now(timezone.utc).isoformat(), | ||
| "run_id": run_id, | ||
| "duration": 10, | ||
| "emissions_sum": 0.001, | ||
| "emissions_rate": 0.0001, | ||
| "cpu_power": 0.0, | ||
| "gpu_power": 0.0, | ||
| "ram_power": 0.0, | ||
| "cpu_energy": 0.0, | ||
| "gpu_energy": 0.0, | ||
| "ram_energy": 0.0, | ||
| "energy_consumed": 0.01, | ||
| "wue": 0, | ||
| } | ||
| emission_response = requests.post( | ||
| _api_url("/emissions"), | ||
| json=emission_payload, | ||
| headers={"x-api-token": settings.api_key}, | ||
| timeout=10, | ||
| ) | ||
| assert emission_response.status_code == 201, emission_response.text | ||
| assert uuid.UUID(emission_response.json()) | ||
|
|
||
|
|
||
| def test_local_post_public_summary_helper(): | ||
| settings = _local_settings() | ||
| assert ( | ||
| post_public_summary( | ||
| settings, {"os": "Linux", "tracking_mode": "process"}, _sample_emissions() | ||
| ) | ||
| is True | ||
| ) |
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
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.
does this work? Should it not be
x_api_token: str = Header(None, alias="x-api-token")?