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.electricitymaps.com/v3/carbon-intensity/latest', emission_factor_type='lifecycle', 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)
emission_factor_type (str)
env_file_path (str | None)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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.electricitymaps.com/v3/carbon-intensity/latest', emission_factor_type='lifecycle'))#
Tracarbon builder for building Tracarbon.
- Parameters:
exporter (Exporter | None)
location (Location | None)
configuration (TracarbonConfiguration)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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=<factory>)#
Tracarbon report to store running statistics.
- Parameters:
start_time (datetime | None)
end_time (datetime | None)
metric_report (Dict[str, MetricReport])
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.containers.Container(*, name, cpu_usage, memory_usage)#
Container of Kubernetes.
- Parameters:
name (str)
cpu_usage (float)
memory_usage (float)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
- 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]
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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])
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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 values to the requested unit.
- Parameters:
unit (EnergyUsageUnit) – the target energy usage unit for the conversion
- Return type:
None
- get_energy_usage_on_type(usage_type)#
Get the energy usage based on the type.
- Param:
usage_type: the type of energy to return
- Returns:
the energy of the type
- Parameters:
usage_type (UsageType)
- Return type:
float | None
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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.AMDGPU#
AMD GPU information using rocm-smi or amd-smi. Supports multiple GPUs by summing power consumption across all detected GPUs.
- classmethod get_gpu_power_usage()#
Get the AMD GPU power usage in watts. Supports multiple GPUs by summing power consumption.
- Returns:
the total gpu power usage in W
- Return type:
float
- classmethod launch_shell_command()#
Launch a shell command to query AMD GPU power. Tries rocm-smi first, then falls back to amd-smi.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.gpu.AppleSiliconGPU#
Apple Silicon GPU information using powermetrics. Note: powermetrics may require sudo privileges for full access.
- classmethod get_gpu_power_usage()#
Get the Apple Silicon GPU power usage in watts.
- Returns:
the gpu power usage in W
- Return type:
float
- classmethod launch_shell_command()#
Launch powermetrics to query GPU power. Delegates to AppleSiliconPowerMetrics.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.gpu.AppleSiliconPowerMetrics#
Apple Silicon power metrics using powermetrics. Parses CPU, GPU, and ANE power from powermetrics output. Note: powermetrics requires sudo privileges.
- classmethod get_combined_power()#
Get the combined power (CPU + GPU + ANE) in watts. Falls back to summing individual components if Combined Power line is not found.
- Returns:
combined power in watts, or None if unavailable
- Return type:
float | None
- classmethod get_power_breakdown()#
Get CPU, GPU, and ANE power in watts from powermetrics.
- Returns:
tuple of (cpu_power, gpu_power, ane_power) in watts, None if unavailable
- Return type:
Tuple[float | None, float | None, float | None]
- classmethod launch_shell_command()#
Launch powermetrics to query CPU and GPU power.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.gpu.GPUInfo#
GPU information with auto-detection and graceful fallback. Tries all available GPU types and returns 0.0 if none found.
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts. Auto-detects GPU type and falls back to 0.0 if no GPU is found.
- Returns:
the gpu power usage in W, or 0.0 if no GPU detected
- Return type:
float
- classmethod get_gpu_power_usage_or_none()#
Get the GPU power usage in watts, or None if no GPU is available.
- Returns:
the gpu power usage in W, or None if no GPU detected
- Return type:
float | None
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.gpu.NvidiaGPU#
Nvidia GPU information. Supports multiple GPUs by summing power consumption across all detected GPUs.
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts. Supports multiple GPUs by summing power consumption.
- Returns:
the total gpu power usage in W
- Return type:
float
- classmethod launch_shell_command()#
Launch a shell command to query GPU power.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.rapl.RAPL(*, path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results=<factory>, file_list=<factory>)#
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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.amd_rapl.AMDRAPL(*, hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results=<factory>, energy_files=<factory>)#
AMD RAPL to read energy consumption via HWMON interface.
The amd_energy driver exposes energy counters at: /sys/class/hwmon/hwmon*/energy*_input (in microjoules) /sys/class/hwmon/hwmon*/energy*_label (domain label)
Labels follow the pattern: - Esocket0, Esocket1, … : Package/socket level energy - Ecore0, Ecore1, … : Per-core energy
- Parameters:
hwmon_base_path (str)
amd_energy_path (str | None)
rapl_results (Dict[str, AMDRAPLResult])
energy_files (List[str])
- async get_amd_rapl_power_usage()#
Read the AMD RAPL energy measurements from HWMON files.
- Returns:
List of AMD RAPL results
- Return type:
List[AMDRAPLResult]
- get_energy_files_list()#
Get the list of energy files from the AMD HWMON interface.
- Raises:
ValueError – If AMD energy interface is not available
- Return type:
None
- async get_energy_report()#
Get the energy report based on AMD RAPL HWMON readings.
AMD RAPL domains: - Esocket*: Package-level power (similar to Intel’s package domain) - Ecore*: Per-core power
Note: AMD RAPL does not expose separate RAM domain via HWMON. For RAM measurements, the package domain includes integrated memory controller.
- Returns:
EnergyUsage report from AMD RAPL measurements
- Return type:
- async is_amd_rapl_compatible()#
Check if AMD RAPL energy measurement is available via HWMON.
- Returns:
True if AMD energy HWMON interface is available
- Return type:
bool
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.amd_rapl.AMDRAPLResult(*, name, label, energy_uj, timestamp)#
AMD RAPL result after reading the HWMON energy files.
- Parameters:
name (str)
label (str)
energy_uj (float)
timestamp (datetime)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.AMDRAPL(*, hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results=<factory>, energy_files=<factory>)#
AMD RAPL to read energy consumption via HWMON interface.
The amd_energy driver exposes energy counters at: /sys/class/hwmon/hwmon*/energy*_input (in microjoules) /sys/class/hwmon/hwmon*/energy*_label (domain label)
Labels follow the pattern: - Esocket0, Esocket1, … : Package/socket level energy - Ecore0, Ecore1, … : Per-core energy
- Parameters:
hwmon_base_path (str)
amd_energy_path (str | None)
rapl_results (Dict[str, AMDRAPLResult])
energy_files (List[str])
- async get_amd_rapl_power_usage()#
Read the AMD RAPL energy measurements from HWMON files.
- Returns:
List of AMD RAPL results
- Return type:
List[AMDRAPLResult]
- get_energy_files_list()#
Get the list of energy files from the AMD HWMON interface.
- Raises:
ValueError – If AMD energy interface is not available
- Return type:
None
- async get_energy_report()#
Get the energy report based on AMD RAPL HWMON readings.
AMD RAPL domains: - Esocket*: Package-level power (similar to Intel’s package domain) - Ecore*: Per-core power
Note: AMD RAPL does not expose separate RAM domain via HWMON. For RAM measurements, the package domain includes integrated memory controller.
- Returns:
EnergyUsage report from AMD RAPL measurements
- Return type:
- async is_amd_rapl_compatible()#
Check if AMD RAPL energy measurement is available via HWMON.
- Returns:
True if AMD energy HWMON interface is available
- Return type:
bool
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.AppleSiliconPowerMetrics#
Apple Silicon power metrics using powermetrics. Parses CPU, GPU, and ANE power from powermetrics output. Note: powermetrics requires sudo privileges.
- classmethod get_combined_power()#
Get the combined power (CPU + GPU + ANE) in watts. Falls back to summing individual components if Combined Power line is not found.
- Returns:
combined power in watts, or None if unavailable
- Return type:
float | None
- classmethod get_power_breakdown()#
Get CPU, GPU, and ANE power in watts from powermetrics.
- Returns:
tuple of (cpu_power, gpu_power, ane_power) in watts, None if unavailable
- Return type:
Tuple[float | None, float | None, float | None]
- classmethod launch_shell_command()#
Launch powermetrics to query CPU and GPU power.
- Returns:
result of the shell command and returncode
- Return type:
Tuple[bytes, int]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.AzureEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#
The Azure VM Energy Consumption.
- Parameters:
instance_type (str)
init (bool)
min_watts (float)
max_watts (float)
vcpus (float)
memory_gb (float)
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.CloudEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#
Base class for cloud provider energy consumption. Uses linear interpolation between min and max watts based on CPU usage.
- Parameters:
instance_type (str)
init (bool)
min_watts (float)
max_watts (float)
vcpus (float)
memory_gb (float)
- async get_energy_usage()#
Run the sensor and generate energy usage using linear interpolation.
- Returns:
the generated energy usage.
- Return type:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.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 values to the requested unit.
- Parameters:
unit (EnergyUsageUnit) – the target energy usage unit for the conversion
- Return type:
None
- get_energy_usage_on_type(usage_type)#
Get the energy usage based on the type.
- Param:
usage_type: the type of energy to return
- Returns:
the energy of the type
- Parameters:
usage_type (UsageType)
- Return type:
float | None
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.GCPEnergyConsumption(instance_type, *, init=False, min_watts, max_watts, vcpus, memory_gb)#
The GCP Compute Engine Energy Consumption.
- Parameters:
instance_type (str)
init (bool)
min_watts (float)
max_watts (float)
vcpus (float)
memory_gb (float)
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.GPUInfo#
GPU information with auto-detection and graceful fallback. Tries all available GPU types and returns 0.0 if none found.
- classmethod get_gpu_power_usage()#
Get the GPU power usage in watts. Auto-detects GPU type and falls back to 0.0 if no GPU is found.
- Returns:
the gpu power usage in W, or 0.0 if no GPU detected
- Return type:
float
- classmethod get_gpu_power_usage_or_none()#
Get the GPU power usage in watts, or None if no GPU is available.
- Returns:
the gpu power usage in W, or None if no GPU detected
- Return type:
float | None
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.LinuxEnergyConsumption(*, init=False, rapl=RAPL(path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results={}, file_list=[]), amd_rapl=AMDRAPL(hwmon_base_path='/sys/class/hwmon', amd_energy_path=None, rapl_results={}, energy_files=[]))#
Energy Consumption of a Linux device.
Supports both Intel and AMD processors via RAPL: - Intel: Uses powercap interface at /sys/class/powercap/intel-rapl - AMD (kernel 5.8+): Also uses powercap interface (same path as Intel) - AMD (older/alternative): Uses HWMON interface via amd_energy driver
- async get_energy_usage()#
Run the sensor and generate energy usage.
Tries sensors in order of preference: 1. Intel RAPL (powercap) - works for Intel and AMD on kernel 5.8+ 2. AMD RAPL (HWMON) - fallback for AMD with amd_energy driver
GPU power is also queried if available (NVIDIA or AMD GPU).
- Returns:
the generated energy usage.
- Return type:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Args:
self: The BaseModel instance. context: The context.
- Parameters:
self (BaseModel)
context (Any)
- Return type:
None
- class tracarbon.hardwares.sensors.MacEnergyConsumption(*, init=False, shell_command="ioreg -rw0 -a -c AppleSmartBattery | plutil -extract '0.BatteryData.AdapterPower' raw -")#
Energy Consumption of a Mac in watts.
Uses powermetrics as the primary sensor for Apple Silicon, providing per-component power breakdown (CPU, GPU, ANE). Works on battery and plugged in.
Falls back to ioreg AdapterPower if powermetrics is not available (requires sudo). The ioreg fallback only works when plugged into a wall adapter.
- Parameters:
init (bool)
shell_command (str)
- async get_energy_usage()#
Run the sensor and generate energy usage.
Tries powermetrics first for per-component breakdown (CPU, GPU, ANE), falls back to ioreg AdapterPower + separate GPU query.
- Returns:
the generated energy usage.
- Return type:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_post_init(context, /)#
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Args:
self: The BaseModel instance. context: The context.
- Parameters:
self (BaseModel)
context (Any)
- Return type:
None
- class tracarbon.hardwares.sensors.RAPL(*, path='/sys/class/powercap/intel-rapl', rapl_separator=':', rapl_results=<factory>, file_list=<factory>)#
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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.hardwares.sensors.Sensor#
The Sensor contract.
- abstract async get_energy_usage()#
Run the sensor and generate energy usage in watt.
- Returns:
the generated energy usage.
- Return type:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Exporters#
- class tracarbon.exporters.exporter.Exporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>)#
The Exporter interface.
- Parameters:
metric_generators (List[MetricGenerator])
event (Event | None)
stopped (bool)
metric_prefix_name (str | None)
metric_report (Dict[str, MetricReport])
- 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
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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=<factory>)#
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]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.exporter.MetricGenerator(*, metrics, platform='Linux', location=None)#
MetricGenerator generates metrics for the Exporter.
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.exporter.Tag(*, key, value)#
Tag for a metric.
- Parameters:
key (str)
value (str)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.stdout.StdoutExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>)#
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
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.datadog_exporter.DatadogExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, 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
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.json_exporter.JSONExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, path='', 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()#
Close the JSON array if needed by appending a 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
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.exporters.prometheus_exporter.PrometheusExporter(*, metric_generators, event=None, stopped=False, metric_prefix_name=None, metric_report=<factory>, prometheus_metrics=<factory>, 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
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
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:
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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
- get_carbon_usage_on_type(usage_type)#
Get the carbon usage based on the type.
- Param:
usage_type: the type of energy to return
- Returns:
the carbon of the type
- Parameters:
usage_type (UsageType)
- Return type:
float | None
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.emissions.carbon_emissions.CarbonUsageUnit(value)#
Carbon usage unit.
Locations#
- class tracarbon.locations.location.CarbonIntensitySource(value)#
An enumeration.
- class tracarbon.locations.location.EmissionFactorType(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, emission_factor_type=EmissionFactorType.LIFECYCLE)#
Generic Location.
- Parameters:
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- abstract async get_latest_co2g_kwh()#
Get the latest co2g_kwh for France.
- Returns:
the latest co2g_kwh
- Return type:
float
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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, emission_factor_type=EmissionFactorType.LIFECYCLE)#
AWS Location.
- Parameters:
region_name (str)
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- 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
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.locations.country.AzureLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0, emission_factor_type=EmissionFactorType.LIFECYCLE)#
Azure Location.
- Parameters:
region_name (str)
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.locations.country.CloudLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0, emission_factor_type=EmissionFactorType.LIFECYCLE)#
Base class for cloud provider locations.
- Parameters:
region_name (str)
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- 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 this cloud provider.
- Returns:
the latest co2g_kwh
- Return type:
float
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.locations.country.Country(*, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0, emission_factor_type=EmissionFactorType.LIFECYCLE)#
Country definition.
- Parameters:
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- 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='https://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 Electricity Maps API or CO2 Signal API.
- Returns:
the latest CO2g_kwh
- Return type:
float
- classmethod get_location(co2signal_api_key=None, co2signal_url=None, country_code_alpha_iso_2=None, emission_factor_type=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 or Electricity Maps API.
co2signal_url (str | None) – api url for fetching the carbon intensity API endpoint.
emission_factor_type (str | None) – the emission factor type (lifecycle or direct) for Electricity Maps API.
- Returns:
the country
- Return type:
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class tracarbon.locations.country.GCPLocation(region_name, *, name, co2g_kwh_source=CarbonIntensitySource.FILE, co2signal_api_key=None, co2signal_url=None, co2g_kwh=0.0, emission_factor_type=EmissionFactorType.LIFECYCLE)#
GCP Location.
- Parameters:
region_name (str)
name (str)
co2g_kwh_source (CarbonIntensitySource)
co2signal_api_key (str | None)
co2signal_url (str | None)
co2g_kwh (float)
emission_factor_type (EmissionFactorType)
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Exceptions#
- exception tracarbon.exceptions.AWSSensorException#
Error in the AWS Sensor Error.
- exception tracarbon.exceptions.AzureSensorException#
Error in the Azure Sensor.
- 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.GCPSensorException#
Error in the GCP Sensor.
- 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)
- async generate()#
Generate metrics for the carbon emission.
- Returns:
an async generator of the metrics
- Return type:
AsyncGenerator[Metric, None]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
metrics (List[Metric])
platform (str)
carbon_emission (CarbonEmission)
kubernetes (Kubernetes)
co2signal_api_key (str | None)
- async generate()#
Generate metrics for the carbon emission with Kubernetes.
- Returns:
an async generator of the metrics
- Return type:
AsyncGenerator[Metric, None]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
- async generate()#
Generate a metric for energy consumption.
- Returns:
an async generator of the metrics
- Return type:
AsyncGenerator[Metric, None]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- 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)
- async generate()#
Generate metrics for the energy consumption with Kubernetes.
- Returns:
an async generator of the metrics
- Return type:
AsyncGenerator[Metric, None]
- model_config: ClassVar[ConfigDict] = {}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].