API Reference#
CLI#
- tracarbon.cli.add_containers_generator(location)#
Add metric generators for containers if available
- Param:
country for the metric generators of containers
- Returns:
the list of metric generators for containers
- Parameters:
location (Country) –
- Return type:
List[MetricGenerator]
- tracarbon.cli.get_exporter(exporter_name, metric_generators, tracarbon_builder=None)#
Get the exporter based on the name with its metrics.
- Parameters:
exporter_name (str) – the name of the exporter
metric_generators (List[MetricGenerator]) – the list of the metrics generators
tracarbon_builder (TracarbonBuilder | None) – the configuration of Tracarbon
- Returns:
the configured exporter
- Return type:
- tracarbon.cli.list_exporters(displayed=True)#
List all the exporters available.
- Parameters:
displayed (bool) –
- Return type:
List[str]
- tracarbon.cli.run(exporter_name='Stdout', country_code_alpha_iso_2=None, containers=False)#
Run Tracarbon.
- Parameters:
exporter_name (str) –
country_code_alpha_iso_2 (str | None) –
containers (bool) –
- Return type:
None
- tracarbon.cli.run_metrics(exporter_name, country_code_alpha_iso_2=None, running=True, containers=False)#
Run the metrics with the selected exporter
- Parameters:
country_code_alpha_iso_2 (str | None) – the alpha iso2 country name where it’s running
running (bool) – keep running the metrics
exporter_name (str) – the exporter name to run
containers (bool) – activate the containers feature
- Returns:
- Return type:
None
Configuration#
- class tracarbon.conf.TracarbonConfiguration(metric_prefix_name='tracarbon', interval_in_seconds=60, log_level='INFO', co2signal_api_key='', co2signal_url='https://api.co2signal.com/v1/latest?countryCode=', env_file_path=None)#
The Configuration of Tracarbon.
- Parameters:
metric_prefix_name (str) –
interval_in_seconds (int) –
log_level (str) –
co2signal_api_key (str) –
co2signal_url (str) –
env_file_path (str | None) –
- tracarbon.conf.logger_configuration(level)#
Configure the logger format.
- Parameters:
level (str) –
- Return type:
None
Builder#
- class tracarbon.builder.Tracarbon(configuration, exporter, location)#
Tracarbon instance.
- Parameters:
configuration (TracarbonConfiguration) –
exporter (Exporter) –
location (Location) –
- start()#
Start Tracarbon.
- Return type:
None
- stop()#
Stop Tracarbon.
- Return type:
None
- class tracarbon.builder.TracarbonBuilder(*, exporter=None, location=None, configuration=TracarbonConfiguration(metric_prefix_name='test', log_level='INFO', interval_in_seconds=1, co2signal_api_key='', co2signal_url='https://api.co2signal.com/v1/latest?countryCode='))#
Tracarbon builder for building Tracarbon.
- Parameters:
exporter (Exporter | None) –
location (Location | None) –
configuration (TracarbonConfiguration) –
- with_exporter(exporter)#
Add an exporter to the builder. :param exporter: the exporter :return:
- Parameters:
exporter (Exporter) –
- Return type:
- class tracarbon.builder.TracarbonReport(*, start_time=None, end_time=None, metric_report={})#
Tracarbon report to store running statistics.
- Parameters:
start_time (datetime | None) –
end_time (datetime | None) –
metric_report (Dict[str, MetricReport]) –
- class Config#
Pydantic configuration.
Hardware#
- class tracarbon.hardwares.hardware.HardwareInfo#
Hardware information.
- static get_cpu_usage(interval=None)#
Get the CPU load percentage usage.
- Parameters:
interval (float | None) – the minimal interval to wait between two consecutive measures
- Returns:
the CPU load in %
- Return type:
float
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts.
- Returns:
the gpu power usage in W
- Return type:
float
- static get_memory_total()#
Get the total physical memory available.
- Returns:
the total physical memory available
- Return type:
float
- static get_memory_usage()#
Get the local memory usage.
- Returns:
the memory used in percentage
- Return type:
float
- static get_number_of_cores(logical=True)#
Get the number of CPU’s cores.
- Param:
logical: core as logical included
- Returns:
the number of CPU’s cores
- Parameters:
logical (bool) –
- Return type:
int
- static get_platform()#
Get the platform name.
- Returns:
the name of the platform
- Return type:
str
- class tracarbon.hardwares.containers.Container(*, name, cpu_usage, memory_usage)#
Container of Kubernetes.
- Parameters:
name (str) –
cpu_usage (float) –
memory_usage (float) –
- class tracarbon.hardwares.containers.Kubernetes(*, namespaces=None, api, group='metrics.k8s.io', version='v1beta1')#
Kubernetes client.
- Parameters:
namespaces (List[str] | None) –
api (CustomObjectsApi) –
group (str) –
version (str) –
- class Config#
Pydantic configuration.
- get_pods_usage(namespace=None)#
Get Pods with usage.
- Param:
namespaces: list of namespaces for getting the pods.
- Returns:
an iterator of the pods
- Parameters:
namespace (str | None) –
- Return type:
Iterator[Pod]
- refresh_namespaces()#
Refresh the names of the namespaces.
- Return type:
None
- class tracarbon.hardwares.containers.Pod(*, name, namespace, containers)#
Pod for Kubernetes.
- Parameters:
name (str) –
namespace (str) –
containers (List[Container]) –
- class tracarbon.hardwares.energy.EnergyUsage(*, host_energy_usage=0.0, cpu_energy_usage=None, memory_energy_usage=None, gpu_energy_usage=None, unit=EnergyUsageUnit.WATT)#
Energy report in watts.
- Parameters:
host_energy_usage (float) –
cpu_energy_usage (float | None) –
memory_energy_usage (float | None) –
gpu_energy_usage (float | None) –
unit (EnergyUsageUnit) –
- convert_unit(unit)#
Convert the EnergyUsage with the right energy usage type
- Param:
unit: the energy usage unit for the conversion
- Parameters:
unit (EnergyUsageUnit) –
- Return type:
None
- class tracarbon.hardwares.energy.EnergyUsageUnit(value)#
Energy usage unit.
- class tracarbon.hardwares.energy.Power#
Power utility
- static co2g_from_watts_hour(watts_hour, co2g_per_kwh)#
Calculate the CO2g generated using watt-hours and the CO2g/kwh.
- Returns:
the CO2g generated by the energy consumption
- Parameters:
watts_hour (float) –
co2g_per_kwh (float) –
- Return type:
float
- static watts_from_microjoules(uj)#
Get watts from microjoules.
- Param:
uj: energy in microjoules
- Returns:
watts
- Parameters:
uj (float) –
- Return type:
float
- static watts_to_watt_hours(watts, previous_energy_measurement_time=None)#
Convert current watts to watt-hours W/h using the previous energy measurement.
- Parameters:
watts (float) – the wattage in W
previous_energy_measurement_time (datetime | None) – the previous measurement time
- Returns:
watt-hours W/h
- Return type:
float
- class tracarbon.hardwares.energy.UsageType(value)#
Usage type.
- class tracarbon.hardwares.gpu.GPUInfo#
GPU information.
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts.
- Returns:
the gpu power usage in W
- Return type:
float
- class tracarbon.hardwares.gpu.NvidiaGPU#
Nvidia GPU information.
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts.
- Returns:
the gpu power usage in W
- Return type:
float
- classmethod launch_shell_command()#
Launch a shell command.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- class tracarbon.hardwares.rapl.RAPL(*, path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results={}, file_list=[])#
RAPL to read energy consumption with Intel hardware
- Parameters:
path (str) –
rapl_separator (str) –
rapl_results (Dict[str, RAPLResult]) –
file_list (List[str]) –
- async get_energy_report()#
Get the energy report based on RAPL.
- Returns:
the energy usage report of the RAPL measurements
- Return type:
- get_rapl_files_list()#
Get the list of files containing RAPL energy measurements. Raise error if it’s the hardware is not compatible with RAPL.
- Returns:
the list of files path containing RAPL energy measurements.
- Return type:
None
- async get_rapl_power_usage()#
Read the RAPL energy measurements files on paths provided.
If energy_uj is greater than max_energy_range_uj, the value is set to 0. In this case, max_energy_range_uj contanst must be returned.
- Returns:
a list of the RAPL results.
- Return type:
List[RAPLResult]
- is_rapl_compatible()#
Check if the path of the hardware for reading RAPL energy measurements exists. :return: if the RAPL files path exists
- Return type:
bool
- class tracarbon.hardwares.rapl.RAPLResult(*, name, energy_uj, max_energy_uj, timestamp)#
RAPL result after reading the RAPL registry.
- Parameters:
name (str) –
energy_uj (float) –
max_energy_uj (float) –
timestamp (datetime) –
- class tracarbon.hardwares.sensors.AWSEC2EnergyConsumption(instance_type, *, init=False, cpu_idle, cpu_at_10, cpu_at_50, cpu_at_100, memory_idle, memory_at_10, memory_at_50, memory_at_100, has_gpu, delta_full_machine)#
The AWS EC2 Energy Consumption.
- Parameters:
instance_type (str) –
init (bool) –
cpu_idle (float) –
cpu_at_10 (float) –
cpu_at_50 (float) –
cpu_at_100 (float) –
memory_idle (float) –
memory_at_10 (float) –
memory_at_50 (float) –
memory_at_100 (float) –
has_gpu (bool) –
delta_full_machine (float) –
- async get_energy_usage()#
Run the sensor and generate energy usage.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.hardwares.sensors.EnergyConsumption(*, init=False)#
A sensor to calculate the energy consumption.
- Parameters:
init (bool) –
- static from_platform(platform='Linux')#
Get the energy consumption from the local platform or cloud provider.
- Returns:
the Energy Consumption
- Parameters:
platform (str) –
- Return type:
- abstract async get_energy_usage()#
Run the sensor and generate energy usage.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.hardwares.sensors.LinuxEnergyConsumption(*, init=False, rapl=RAPL(path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results={}, file_list=[]))#
Energy Consumption of a Linux device: fvaleye/tracarbon#1
- Parameters:
init (bool) –
rapl (RAPL) –
- async get_energy_usage()#
Run the sensor and generate energy usage.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.hardwares.sensors.MacEnergyConsumption(*, init=False, shell_command='/usr/sbin/ioreg -rw0 -c AppleSmartBattery | grep BatteryData | grep -o \'"AdapterPower"=[0-9]*\' | cut -c 16- | xargs -I % lldb --batch -o "print/f %" | grep -o \'$0 = [0-9.]*\' | cut -c 6-')#
Energy Consumption of the Mac, working only if it’s plugged into plugged-in wall adapter, in watts.
- Parameters:
init (bool) –
shell_command (str) –
- async get_energy_usage()#
Run the sensor and generate energy usage.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.hardwares.sensors.Sensor#
The Sensor contract.
- class Config#
Pydantic configuration.
- abstract async get_energy_usage()#
Run the sensor and generate energy usage in watt.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.hardwares.sensors.WindowsEnergyConsumption(*, init=False)#
Energy Consumption of a Windows device: fvaleye/tracarbon#2
- Parameters:
init (bool) –
- async get_energy_usage()#
Run the sensor and generate energy usage.
- Returns:
the generated energy usage.
- Return type:
Exporters#
- class tracarbon.exporters.exporter.Exporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report={})#
The Exporter interface.
- Parameters:
metric_generators (List[MetricGenerator]) –
event (Event | None) –
stopped (bool) –
metric_prefix_name (str | None) –
metric_report (Dict[str, MetricReport]) –
- class Config#
Pydantic configuration.
- async add_metric_to_report(metric, value)#
Add the generated metric to the report asynchronously.
- Parameters:
metric (Metric) – the metric to add
value (float) – the metric value to add
- Returns:
- Return type:
- abstract classmethod get_name()#
Get the name of the exporter.
- Returns:
the Exporter’s name
- Return type:
str
- abstract async launch(metric_generator)#
Launch the exporter. Add the metric generator to the metric reporter.
- Parameters:
metric_generator (MetricGenerator) – the metric generator
- Return type:
None
- start(interval_in_seconds)#
Start the exporter and a dedicated timer configured with the configured timeout.
- Param:
interval_in_seconds: the interval for the timer
- Parameters:
interval_in_seconds (int) –
- Return type:
None
- stop()#
Stop the explorer and the associated timer.
- Returns:
- Return type:
None
- class tracarbon.exporters.exporter.Metric(*, name, value, tags=[])#
Global metric to use for the exporters.
- Parameters:
name (str) –
value (Callable[[], Awaitable[float]]) –
tags (List[Tag]) –
- format_name(metric_prefix_name=None, separator='.')#
Format the name of the metric with a prefix and separator.
- Parameters:
metric_prefix_name (str | None) – the prefix to insert before the separator and the name.
separator (str) – the separator to use between the prefix and the name.
- Return type:
str
- format_tags(separator=':')#
Format tags with a separator.
- Parameters:
separator (str) – the separator to insert between the key and value.
- Return type:
List[str]
- class tracarbon.exporters.exporter.MetricGenerator(*, metrics, platform='Linux', location=None)#
MetricGenerator generates metrics for the Exporter.
- class tracarbon.exporters.exporter.MetricReport(*, exporter_name, metric, average_interval_in_seconds=None, last_report_time=None, total=0.0, average=0.0, minimum=1.7976931348623157e+308, maximum=0.0, call_count=0)#
MetricReport is a report of the generated metrics.
- Parameters:
exporter_name (str) –
metric (Metric) –
average_interval_in_seconds (float | None) –
last_report_time (datetime | None) –
total (float) –
average (float) –
minimum (float) –
maximum (float) –
call_count (int) –
- class Config#
Pydantic configuration.
- class tracarbon.exporters.exporter.Tag(*, key, value)#
Tag for a metric.
- Parameters:
key (str) –
value (str) –
- class tracarbon.exporters.stdout.StdoutExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report={})#
Print the metrics to Stdout.
- Parameters:
metric_generators (List[MetricGenerator]) –
event (Event | None) –
stopped (bool) –
metric_prefix_name (str | None) –
metric_report (Dict[str, MetricReport]) –
- classmethod get_name()#
Get the name of the exporter.
- Returns:
the Exporter’s name
- Return type:
str
- async launch(metric_generator)#
Launch the Stdout exporter with the metrics.
- Parameters:
metric_generator (MetricGenerator) – the metric generator
- Return type:
None
- class tracarbon.exporters.datadog_exporter.DatadogExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report={}, api_key=None, app_key=None, stats=None, disable_buffering=False, datadog_flush_interval=10)#
Datadog exporter for the metrics.
- Parameters:
metric_generators (List[MetricGenerator]) –
event (Event | None) –
stopped (bool) –
metric_prefix_name (str | None) –
metric_report (Dict[str, MetricReport]) –
api_key (str | None) –
app_key (str | None) –
stats (ThreadStats | None) –
disable_buffering (bool) –
datadog_flush_interval (int) –
- classmethod get_name()#
Get the name of the exporter.
- Returns:
the Exporter’s name
- Return type:
str
- async launch(metric_generator)#
Launch the Datadog exporter with the metrics.
- Parameters:
metric_generator (MetricGenerator) – the metric generators
- Returns:
- Return type:
None
- class tracarbon.exporters.json_exporter.JSONExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report={}, path='tracarbon_export_13_11_2024.json', indent=4)#
Write the metrics to a local JSON file.
- Parameters:
metric_generators (List[MetricGenerator]) –
event (Event | None) –
stopped (bool) –
metric_prefix_name (str | None) –
metric_report (Dict[str, MetricReport]) –
path (str) –
indent (int) –
- flush()#
Flush the file and add the closing bracket.
- Return type:
None
- classmethod get_name()#
Get the name of the exporter.
- Returns:
the Exporter’s name
- Return type:
str
- async launch(metric_generator)#
Launch the Stdout exporter with the metrics.
- Parameters:
metric_generator (MetricGenerator) – the metric generator
- Return type:
None
- class tracarbon.exporters.prometheus_exporter.PrometheusExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report={}, prometheus_metrics={}, address=None, port=None)#
Send the metrics to Prometheus by running an HTTP server for the metrics exposure.
- Parameters:
metric_generators (List[MetricGenerator]) –
event (Event | None) –
stopped (bool) –
metric_prefix_name (str | None) –
metric_report (Dict[str, MetricReport]) –
prometheus_metrics (Dict[str, Gauge]) –
address (str | None) –
port (int | None) –
- classmethod get_name()#
Get the name of the exporter.
- Returns:
the Exporter’s name
- Return type:
str
- async launch(metric_generator)#
Launch the Prometheus exporter with the metrics.
- Parameters:
metric_generator (MetricGenerator) – the metric generator
- Return type:
None
Emissions#
- class tracarbon.emissions.carbon_emissions.CarbonEmission(*, location, energy_consumption, previous_energy_consumption_time=None)#
Carbon Metric sensor in watts per second to calculate the CO2g/kwh emitted.
- Parameters:
location (Location) –
energy_consumption (EnergyConsumption) –
previous_energy_consumption_time (datetime | None) –
- async get_co2_usage()#
Run the Carbon Emission sensor and get the carbon emission generated.
- Returns:
the carbon usage.
- Return type:
- async get_energy_usage()#
Generate energy usage.
- Returns:
the generated energy usage.
- Return type:
- class tracarbon.emissions.carbon_emissions.CarbonUsage(*, host_carbon_usage=0.0, cpu_carbon_usage=None, memory_carbon_usage=None, gpu_carbon_usage=None, unit=CarbonUsageUnit.CO2_G)#
Carbon Usage of the different types.
- Parameters:
host_carbon_usage (float) –
cpu_carbon_usage (float | None) –
memory_carbon_usage (float | None) –
gpu_carbon_usage (float | None) –
unit (CarbonUsageUnit) –
- convert_unit(unit)#
Convert the carbon usage with the right carbon usage type.
- Param:
unit: the carbon usage unit for the conversion
- Parameters:
unit (CarbonUsageUnit) –
- Return type:
None
- class tracarbon.emissions.carbon_emissions.CarbonUsageUnit(value)#
Carbon usage unit.
Locations#
- class tracarbon.locations.location.CarbonIntensitySource(value)#
An enumeration.
- class tracarbon.locations.location.Location(*, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0)#
Generic Location.
- Parameters:
name (str) –
co2g_kwh_source (CarbonIntensitySource) –
co2signal_api_key (str | None) –
co2signal_url (str | None) –
co2g_kwh (float) –
- abstract async get_latest_co2g_kwh()#
Get the latest co2g_kwh for France.
- Returns:
the latest co2g_kwh
- Return type:
float
- async classmethod request(url, headers=None)#
Launch an async request.
- Parameters:
url (str) – url to request
headers (Dict[str, str] | None) – headers to add to the request
- Returns:
the response
- Return type:
Dict[str, Any]
- class tracarbon.locations.country.AWSLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0)#
AWS Location.
- Parameters:
region_name (str) –
name (str) –
co2g_kwh_source (CarbonIntensitySource) –
co2signal_api_key (str | None) –
co2signal_url (str | None) –
co2g_kwh (float) –
- async get_co2g_kwh()#
Get the Co2g per kwh.
- Returns:
the co2g/kwh value
- Return type:
float
- async get_latest_co2g_kwh()#
Get the latest co2g_kwh for AWS.
- Returns:
the latest co2g_kwh
- Return type:
float
- class tracarbon.locations.country.Country(*, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0)#
Country definition.
- Parameters:
name (str) –
co2g_kwh_source (CarbonIntensitySource) –
co2signal_api_key (str | None) –
co2signal_url (str | None) –
co2g_kwh (float) –
- classmethod from_eu_file(country_code_alpha_iso_2)#
Get the country from the file.
- Parameters:
country_code_alpha_iso_2 (str) – the alpha_iso_2 name of the country
- Returns:
- Return type:
- classmethod get_current_country(url='http://ipinfo.io/json', timeout=300)#
Get the client’s country using an internet access.
- Parameters:
url (str) – the url to fetch the country from IP
timeout (int) – the timeout for the request
- Returns:
the client’s country alpha_iso_2 name.
- Return type:
str
- async get_latest_co2g_kwh()#
Get the latest CO2g_kwh for the Location from https://www.co2signal.com/.
- Returns:
the latest CO2g_kwh
- Return type:
float
- classmethod get_location(co2signal_api_key=None, co2signal_url=None, country_code_alpha_iso_2=None)#
Get the current location automatically: on cloud provider or a country.
- Parameters:
country_code_alpha_iso_2 (str | None) – the alpha iso 2 country name.
co2signal_api_key (str | None) – api key for fetching CO2 Signal API.
co2signal_url (str | None) – api url for fetching CO2 Signal API endpoint.
- Returns:
the country
- Return type:
Exceptions#
- exception tracarbon.exceptions.AWSSensorException#
Error in the AWS Sensor Error.
- exception tracarbon.exceptions.CO2SignalAPIKeyIsMissing#
The C02 Signal API key is missing.
- exception tracarbon.exceptions.CloudProviderRegionIsMissing#
The region of the cloud provider is missing.
- exception tracarbon.exceptions.CountryIsMissing#
The country is missing.
- exception tracarbon.exceptions.HardwareNoGPUDetectedException#
The hardware does not have a GPU.
- exception tracarbon.exceptions.HardwareRAPLException#
The hardware is not compatible with RAPL.
- exception tracarbon.exceptions.TracarbonException#
General Tracarbon Exception.
General Metrics#
- class tracarbon.general_metrics.CarbonEmissionGenerator(location=None, *, metrics, platform='Linux', carbon_emission, co2signal_api_key=None)#
Carbon emission generator to generate carbon emissions.
- Parameters:
location (Location | None) –
metrics (List[Metric]) –
platform (str) –
carbon_emission (CarbonEmission) –
co2signal_api_key (str | None) –
- class tracarbon.general_metrics.CarbonEmissionKubernetesGenerator(location, *, metrics, platform='Linux', carbon_emission, kubernetes, co2signal_api_key=None)#
Carbon emission generator to generate carbon emissions of the containers.
- Parameters:
location (Location | None) –
metrics (List[Metric]) –
platform (str) –
carbon_emission (CarbonEmission) –
kubernetes (Kubernetes) –
co2signal_api_key (str | None) –
- class tracarbon.general_metrics.EnergyConsumptionGenerator(location=None, *, metrics, platform='Linux', energy_consumption)#
Energy consumption generator for energy consumption.
- Parameters:
location (Location | None) –
metrics (List[Metric]) –
platform (str) –
energy_consumption (EnergyConsumption) –
- class tracarbon.general_metrics.EnergyConsumptionKubernetesGenerator(*, metrics, platform='Linux', location=None, energy_consumption, kubernetes)#
Energy consumption generator for energy consumption of the containers.
- Parameters:
metrics (List[Metric]) –
platform (str) –
location (Location | None) –
energy_consumption (EnergyConsumption) –
kubernetes (Kubernetes) –