-
Notifications
You must be signed in to change notification settings - Fork 6
Add Metrics and pusher to unstable #475
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
Merged
Merged
Changes from 10 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
71e16f6
Add Metrics and pusher to unstable
Hmnt39 1eef3d4
Call push manager only when metrics_config is available
Hmnt39 eefac40
Add test cases for the metrics
Hmnt39 a537180
Merge branch 'master' of github.com:cognitedata/python-extractor-util…
Hmnt39 01cc9d0
Fix the test discovery issue
Hmnt39 d30f494
Fix the tests
Hmnt39 c0bd7fd
Refactor changes
Hmnt39 c22cf01
Reuse the stable metrics
Hmnt39 37b537e
Merge branch 'master' of github.com:cognitedata/python-extractor-util…
Hmnt39 1c71ae4
Merge branch 'master' of github.com:cognitedata/python-extractor-util…
Hmnt39 278b8b0
Add test case for config values
Hmnt39 9bbc5e8
Merge branch 'master' into DOG-5996-Implement-metrics
Hmnt39 5101df9
Use yaml for config: PR review
Hmnt39 6d6141a
Minor Fixes
Hmnt39 fdfa763
Merge branch 'master' into DOG-5996-Implement-metrics
Hmnt39 aa34f49
Merge branch 'master' into DOG-5996-Implement-metrics
Hmnt39 7575f1d
Add test for the COgniteMetrics Config
Hmnt39 c931f37
Merge branch 'master' into DOG-5996-Implement-metrics
Hmnt39 ac2a117
Merge branch 'master' into DOG-5996-Implement-metrics
Hmnt39 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 |
|---|---|---|
|
|
@@ -8,9 +8,11 @@ | |
| from datetime import timedelta | ||
| from enum import Enum | ||
| from pathlib import Path | ||
| from time import sleep | ||
| from typing import Annotated, Any, Literal, TypeVar | ||
|
|
||
| from humps import kebabize | ||
| from prometheus_client import REGISTRY, start_http_server | ||
| from pydantic import BaseModel, ConfigDict, Field, GetCoreSchemaHandler | ||
| from pydantic_core import CoreSchema, core_schema | ||
| from typing_extensions import assert_never | ||
|
|
@@ -22,15 +24,18 @@ | |
| OAuthClientCertificate, | ||
| OAuthClientCredentials, | ||
| ) | ||
| from cognite.client.data_classes import Asset | ||
| from cognite.extractorutils.configtools._util import _load_certificate_data | ||
| from cognite.extractorutils.exceptions import InvalidConfigError | ||
| from cognite.extractorutils.metrics import AbstractMetricsPusher, CognitePusher, PrometheusPusher | ||
| from cognite.extractorutils.statestore import ( | ||
| AbstractStateStore, | ||
| LocalStateStore, | ||
| NoStateStore, | ||
| RawStateStore, | ||
| ) | ||
| from cognite.extractorutils.threading import CancellationToken | ||
| from cognite.extractorutils.util import EitherId | ||
|
|
||
| __all__ = [ | ||
| "AuthenticationConfig", | ||
|
|
@@ -43,6 +48,7 @@ | |
| "LogFileHandlerConfig", | ||
| "LogHandlerConfig", | ||
| "LogLevel", | ||
| "MetricsConfig", | ||
| "ScheduleConfig", | ||
| "TimeIntervalConfig", | ||
| ] | ||
|
|
@@ -429,6 +435,176 @@ class LogConsoleHandlerConfig(ConfigModel): | |
| LogHandlerConfig = Annotated[LogFileHandlerConfig | LogConsoleHandlerConfig, Field(discriminator="type")] | ||
|
|
||
|
|
||
| class EitherIdConfig(ConfigModel): | ||
| """ | ||
| Configuration parameter representing an ID in CDF, which can either be an external or internal ID. | ||
|
|
||
| An EitherId can only hold one ID type, not both. | ||
| """ | ||
|
|
||
| id: int | None | ||
| external_id: str | None | ||
|
|
||
| @property | ||
| def either_id(self) -> EitherId: | ||
| """ | ||
| Returns an EitherId object based on the current configuration. | ||
|
|
||
| Raises: | ||
| TypeError: If both id and external_id are None, or if both are set. | ||
| """ | ||
| return EitherId(id=self.id, external_id=self.external_id) | ||
|
|
||
|
|
||
| class _PushGatewayConfig(ConfigModel): | ||
| """ | ||
| Configuration for pushing metrics to a Prometheus Push Gateway. | ||
| """ | ||
|
|
||
| host: str | ||
| job_name: str | ||
| username: str | None | ||
| password: str | None | ||
|
|
||
| clear_after: TimeIntervalConfig | None | ||
| push_interval: TimeIntervalConfig = Field(default_factory=lambda: TimeIntervalConfig("30s")) | ||
|
|
||
|
|
||
| class _PromServerConfig(ConfigModel): | ||
| """ | ||
| Configuration for pushing metrics to a Prometheus server. | ||
| """ | ||
|
|
||
| port: int = 9000 | ||
| host: str = "0.0.0.0" | ||
|
|
||
|
|
||
| class _CogniteMetricsConfig(ConfigModel): | ||
| """ | ||
| Configuration for pushing metrics to Cognite Data Fusion. | ||
| """ | ||
|
|
||
| external_id_prefix: str | ||
| asset_name: str | None | ||
| asset_external_id: str | None | ||
| data_set: EitherIdConfig | None = None | ||
|
|
||
| push_interval: TimeIntervalConfig = Field(default_factory=lambda: TimeIntervalConfig("30s")) | ||
|
|
||
|
|
||
| class MetricsPushManager: | ||
| """ | ||
| Manages the pushing of metrics to various backends. | ||
|
|
||
| Starts and stops pushers based on a given configuration. | ||
|
|
||
| Args: | ||
| metrics_config: Configuration for the metrics to be pushed. | ||
| cdf_client: The CDF tenant to upload time series to | ||
| cancellation_token: Event object to be used as a thread cancelation event | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| metrics_config: "MetricsConfig", | ||
| cdf_client: CogniteClient, | ||
| cancellation_token: CancellationToken | None = None, | ||
| ) -> None: | ||
| """ | ||
| Initialize the MetricsPushManager. | ||
| """ | ||
| self.metrics_config = metrics_config | ||
| self.cdf_client = cdf_client | ||
| self.cancellation_token = cancellation_token | ||
| self.pushers: list[AbstractMetricsPusher] = [] | ||
| self.clear_on_stop: dict[AbstractMetricsPusher, int] = {} | ||
|
|
||
| def start(self) -> None: | ||
| """ | ||
| Start all metric pushers. | ||
| """ | ||
| push_gateways = self.metrics_config.push_gateways or [] | ||
| for counter, push_gateway in enumerate(push_gateways): | ||
| prometheus_pusher = PrometheusPusher( | ||
| job_name=push_gateway.job_name, | ||
| username=push_gateway.username, | ||
| password=push_gateway.password, | ||
| url=push_gateway.host, | ||
| push_interval=push_gateway.push_interval.seconds, | ||
| thread_name=f"MetricsPusher_{counter}", | ||
| cancellation_token=self.cancellation_token, | ||
| ) | ||
| prometheus_pusher.start() | ||
| self.pushers.append(prometheus_pusher) | ||
| if push_gateway.clear_after is not None: | ||
| self.clear_on_stop[prometheus_pusher] = push_gateway.clear_after.seconds | ||
|
|
||
| if self.metrics_config.cognite: | ||
|
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. Please add testing for this option too
Contributor
Author
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. Added the tests |
||
| asset = None | ||
| if self.metrics_config.cognite.asset_name and self.metrics_config.cognite.asset_external_id: | ||
| asset = Asset( | ||
| name=self.metrics_config.cognite.asset_name, | ||
| external_id=self.metrics_config.cognite.asset_external_id, | ||
| ) | ||
| cognite_pusher = CognitePusher( | ||
| cdf_client=self.cdf_client, | ||
| external_id_prefix=self.metrics_config.cognite.external_id_prefix, | ||
| push_interval=self.metrics_config.cognite.push_interval.seconds, | ||
| asset=asset, | ||
| data_set=self.metrics_config.cognite.data_set.either_id | ||
| if self.metrics_config.cognite.data_set | ||
| else None, | ||
| thread_name="CogniteMetricsPusher", | ||
| cancellation_token=self.cancellation_token, | ||
| ) | ||
| cognite_pusher.start() | ||
| self.pushers.append(cognite_pusher) | ||
|
|
||
| if self.metrics_config.server: | ||
| start_http_server(self.metrics_config.server.port, self.metrics_config.server.host, registry=REGISTRY) | ||
|
|
||
| def stop(self) -> None: | ||
| """ | ||
| Stop all metric pushers. | ||
| """ | ||
| for pusher in self.pushers: | ||
| pusher.stop() | ||
|
|
||
| # Clear Prometheus pushers gateways if required | ||
| if self.clear_on_stop: | ||
| wait_time = max(self.clear_on_stop.values()) | ||
| sleep(wait_time) | ||
| for pusher in (p for p in self.clear_on_stop if isinstance(p, PrometheusPusher)): | ||
| pusher.clear_gateway() | ||
|
|
||
|
|
||
| class MetricsConfig(ConfigModel): | ||
| """ | ||
| Destination(s) for metrics. | ||
|
|
||
| Including options for one or several Prometheus push gateways, and pushing as CDF Time Series. | ||
| """ | ||
|
|
||
| push_gateways: list[_PushGatewayConfig] | None | ||
| cognite: _CogniteMetricsConfig | None | ||
| server: _PromServerConfig | None | ||
|
|
||
| def create_manager( | ||
| self, cdf_client: CogniteClient, cancellation_token: CancellationToken | None = None | ||
| ) -> MetricsPushManager: | ||
| """ | ||
| Create a MetricsPushManager based on the current configuration. | ||
|
|
||
| Args: | ||
| cdf_client: An instance of CogniteClient to interact with CDF. | ||
| cancellation_token: Optional token to signal cancellation of metric pushing. | ||
|
|
||
| Returns: | ||
| MetricsPushManager: An instance of MetricsPushManager configured with the provided parameters. | ||
| """ | ||
| return MetricsPushManager(self, cdf_client, cancellation_token) | ||
|
|
||
|
|
||
| # Mypy BS | ||
| def _log_handler_default() -> list[LogHandlerConfig]: | ||
| return [LogConsoleHandlerConfig(type="console", level=LogLevel.INFO)] | ||
|
|
||
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
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.
Won't the lack of defaults here means that these config objects will need an explicit
username: nullin config?Could you write a test that actually loads these types from YAML?
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.
Nice catch, as best practices suggest we should have default value defined here. Fix the default value and also added the test case to if a config variable is missing then it doesn't break.