-
Notifications
You must be signed in to change notification settings - Fork 6.7k
Create Client side metrics #14197
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
fosky94
wants to merge
10
commits into
GoogleCloudPlatform:main
Choose a base branch
from
fosky94:main
base: main
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
Create Client side metrics #14197
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
78cf95e
Create Client side metrics
fosky94 f0ec85e
Update license
fosky94 8498cd3
Update main.py
fosky94 8acd7bb
Update main.py
fosky94 2a64545
fix:add tests
fosky94 9fd6c93
style: fix style violations
fosky94 0eb3c90
fix:fix comments from reviewer
fosky94 eee128e
style:remove unused variable lint
fosky94 453ddc9
style:remove global imports lint
fosky94 9a4d353
fix:change version requirements
fosky94 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 |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| # Copyright 2026 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| # [START memorystore_redis_client_side_metrics] | ||
| import os | ||
| import time | ||
|
|
||
| from opentelemetry import metrics, trace | ||
| from opentelemetry.exporter.cloud_monitoring import ( | ||
| CloudMonitoringMetricsExporter, | ||
| ) | ||
| from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter | ||
| from opentelemetry.instrumentation.redis import RedisInstrumentor | ||
| from opentelemetry.sdk.metrics import MeterProvider | ||
| from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader | ||
| from opentelemetry.sdk.trace import TracerProvider | ||
| from opentelemetry.sdk.trace.export import BatchSpanProcessor | ||
| import redis | ||
| from redis.exceptions import ConnectionError, TimeoutError | ||
|
|
||
|
|
||
|
|
||
|
|
||
| def init_telemetry(): | ||
| """Initializes OpenTelemetry with GCP Exporters and returns the SDK objects.""" | ||
| # 1. Initialize Tracing | ||
| tracer_provider = TracerProvider() | ||
| tracer_provider.add_span_processor( | ||
| BatchSpanProcessor(CloudTraceSpanExporter()) | ||
| ) | ||
| trace.set_tracer_provider(tracer_provider) | ||
| tracer = trace.get_tracer("redis.client") | ||
|
|
||
| # 2. Initialize Metrics | ||
| metrics_exporter = CloudMonitoringMetricsExporter() | ||
| metric_reader = PeriodicExportingMetricReader( | ||
| metrics_exporter, export_interval_millis=10000 | ||
| ) | ||
| meter_provider = MeterProvider(metric_readers=[metric_reader]) | ||
| metrics.set_meter_provider(meter_provider) | ||
| meter = metrics.get_meter("redis.metrics") | ||
|
|
||
| # Bundle all metric handlers safely into a dictionary | ||
| redis_metrics = { | ||
| "rtt_hist": meter.create_histogram("redis_client_rtt", unit="ms"), | ||
| "client_block_hist": meter.create_histogram( | ||
| "redis_client_blocking_latency", unit="ms" | ||
| ), | ||
| "app_block_hist": meter.create_histogram( | ||
| "redis_application_blocking_latency", unit="ms" | ||
| ), | ||
| "retry_counter": meter.create_counter("redis_retry_count"), | ||
| "conn_error_counter": meter.create_counter( | ||
| "redis_connectivity_error_count" | ||
| ), | ||
| } | ||
|
|
||
| redis_metrics["retry_counter"].add(0, {"operation": "startup"}) | ||
| redis_metrics["conn_error_counter"].add(0, {"operation": "startup"}) | ||
|
|
||
| # 3. Setup Redis Auto-Instrumentation | ||
| RedisInstrumentor().instrument() | ||
|
|
||
| return tracer, redis_metrics, tracer_provider, meter_provider | ||
|
|
||
|
|
||
| def init_redis_pool(): | ||
| """Initializes and returns the Redis ConnectionPool and Client.""" | ||
| redis_host = os.environ.get("REDISHOST", "localhost") | ||
| redis_port = int(os.environ.get("REDISPORT", 6379)) | ||
|
|
||
| redis_pool = redis.ConnectionPool( | ||
| host=redis_host, | ||
| port=redis_port, | ||
| max_connections=10, | ||
| decode_responses=True, | ||
| ) | ||
| redis_client = redis.Redis(connection_pool=redis_pool) | ||
| return redis_pool, redis_client | ||
|
|
||
|
|
||
| def smart_redis_call( | ||
| operation_name, func, redis_pool, metrics, *args, **kwargs | ||
| ): | ||
| """Executes a Redis operation with metrics and retry handling (No Globals!).""" | ||
| max_retries = 3 | ||
| attempt = 0 | ||
|
|
||
| pool_start = time.time() | ||
| try: | ||
| conn = redis_pool.get_connection() | ||
| redis_pool.release(conn) | ||
| except Exception: | ||
| pass | ||
|
|
||
| if metrics and metrics.get("client_block_hist"): | ||
| metrics["client_block_hist"].record( | ||
| (time.time() - pool_start) * 1000, {"operation": operation_name} | ||
| ) | ||
|
|
||
| while attempt < max_retries: | ||
| try: | ||
| req_start = time.time() | ||
| response = func(*args, **kwargs) | ||
|
|
||
| if metrics and metrics.get("rtt_hist"): | ||
| metrics["rtt_hist"].record( | ||
| (time.time() - req_start) * 1000, | ||
| {"operation": operation_name}, | ||
| ) | ||
|
|
||
| app_start = time.time() | ||
| _ = str(response) | ||
|
|
||
| if metrics and metrics.get("app_block_hist"): | ||
| metrics["app_block_hist"].record( | ||
| (time.time() - app_start) * 1000, | ||
| {"operation": operation_name}, | ||
| ) | ||
|
|
||
| return response | ||
|
fosky94 marked this conversation as resolved.
|
||
|
|
||
| except (ConnectionError, TimeoutError) as e: | ||
| attempt += 1 | ||
| if metrics and metrics.get("conn_error_counter"): | ||
| metrics["conn_error_counter"].add( | ||
| 1, {"operation": operation_name} | ||
| ) | ||
| if metrics and metrics.get("retry_counter"): | ||
| metrics["retry_counter"].add(1, {"operation": operation_name}) | ||
| if attempt >= max_retries: | ||
| raise e | ||
| time.sleep((2**attempt) * 0.1) | ||
|
|
||
| if __name__ == "__main__": | ||
| tracer, redis_metrics, tracer_provider, meter_provider = init_telemetry() | ||
| redis_pool, redis_client = init_redis_pool() | ||
|
|
||
| if tracer: | ||
| with tracer.start_as_current_span("process_user_span"): | ||
| try: | ||
| # Simple write and read operations | ||
| smart_redis_call( | ||
| "set_user", | ||
| redis_client.set, | ||
| redis_pool, | ||
| redis_metrics, | ||
| "user:123", | ||
| "active", | ||
| ) | ||
|
|
||
| result = smart_redis_call( | ||
| "get_user", | ||
| redis_client.get, | ||
| redis_pool, | ||
| redis_metrics, | ||
| "user:123", | ||
| ) | ||
| print(f"Retrieved: {result}") | ||
| except Exception as e: | ||
| print(f"Error: {e}") | ||
|
|
||
| tracer_provider.force_flush() | ||
| meter_provider.force_flush() | ||
| # [END memorystore_redis_client_side_metrics] | ||
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.
Uh oh!
There was an error while loading. Please reload this page.