このガイドでは、 Cloud de Confiance by S3NS Python クライアント ライブラリで OpenTelemetry 分散トレースを構成して使用する方法について説明します。
概要
Cloud de Confiance by S3NS Python クライアント ライブラリには、OpenTelemetry 分散トレースが組み込まれています。この計測により、手動でモンキーパッチを適用することなく、クライアント オペレーション、RPC 呼び出し、再試行動作、ネットワーク レイテンシ、サービス レスポンスを詳細に可視化できます。
主な特徴:
- バックエンドに依存しない: 標準の OpenTelemetry スパンを出力します。トレースは、Cloud Trace、オンプレミスの OpenTelemetry Collector、またはサードパーティのオブザーバビリティ プラットフォームに直接エクスポートできます。
- オプトイン: テレメトリーを必要としないアプリケーションのランタイム オーバーヘッドを回避するため、分散トレースはデフォルトで無効になっています。
- コンテキストの伝播: スパンは、Python の組み込み
contextvarsを使用してアクティブな OpenTelemetry トレース コンテキストに自動的にバインドされ、クライアント呼び出しを受信 HTTP/gRPC リクエストに関連付けます。
トレースの仕組み(スパン階層)
有効にすると、 Cloud de Confiance by S3NS Python クライアント ライブラリは、ユーザー向けのメソッド実行と基盤となるワイヤ試行を明確に分離する、2 レベルの階層型スパン アーキテクチャを出力します。
[Logical Client Method Span] (Parent: covers full method duration, retries, and backoff)
│
├── [Network Attempt Span #1] (Child: First wire call; e.g. transient 503 UNAVAILABLE)
└── [Network Attempt Span #2] (Child: Retry wire call; succeeds 200 OK)
1. 論理クライアント メソッド スパン(親)
- スコープ: 呼び出しから完了まで、クライアント ライブラリのメソッド呼び出しのライフサイクル全体をカプセル化します。
- 期間: すべての再試行、指数バックオフの一時停止、タイムアウト ポリシーが含まれます。
- ID: 完全修飾 RPC メソッド(
google.cloud.secretmanager.v1.SecretManagerService/GetSecretVersionなど)にちなんで命名されます。 - 属性: 論理 RPC メタデータ、宛先サービス、最終的な高レベルの結果をキャプチャします。
2. ネットワーク試行スパン(子)
- スコープ: 論理メソッド スパンの子スパンとして作成され、個々の HTTP/REST または gRPC 物理ネットワーク試行を表します。
- ライフサイクル: ネットワーク試行ごとに新しいスパンが生成されます。オペレーションが最初の試行で成功した場合、1 つの子スパンが記録されます。オペレーションで一時的なエラーが発生して再試行されると、各試行は独自のタイミングとステータスを持つ独立した子スパンとして記録されます。
- 属性: 低レベルのワイヤ ステータス コード、宛先サーバーのアドレス、トランスポートの詳細をキャプチャします。
前提条件とインストール
Cloud de Confiance by S3NS Python クライアント ライブラリのトレースは、標準の OpenTelemetry Python パッケージに依存しています。
1. パッケージをインストール
クライアント ライブラリと gRPC トランスポートの計測:
opentelemetry-apiはgoogle-api-coreとともに自動的にインストールされ、論理メソッド スパンとHTTP/REST(rest)トランスポート スパンをサポートします。- 低レベルの
gRPCトランスポート スパンも記録するには、google-api-core[tracing](opentelemetry-instrumentation-grpcをインストールする)とともにクライアント ライブラリをインストールします。
pip install google-cloud-secret-manager "google-api-core[tracing]"OpenTelemetry SDK(スタンドアロン アプリとコードサンプル用):
- 環境ですでに
TracerProviderが提供されている場合、クライアント ライブラリはopentelemetry-sdkを必要としません。 - ただし、独自のコード(このページのサンプルを含む)で
TracerProviderを構成してスパンをエクスポートするには、opentelemetry-sdkをインストールします。
pip install opentelemetry-sdk- 環境ですでに
本番環境で Cloud Trace または OpenTelemetry Collector にスパンを送信するように OpenTelemetry エクスポータを構成する手順については、OpenTelemetry で Python を設定すると計測方法を選択するをご覧ください。
トレースを有効にする
分散トレースは、環境変数を使用してグローバルに有効にすることも、クライアントごとにプログラムで有効にすることもできます。ClientOptions を使用して渡されるクライアントごとの構成は、環境変数の設定よりも優先されます。
オプション 1: グローバル構成(環境変数)
環境でサポートされているすべての Cloud de Confiance by S3NS Python クライアント ライブラリでトレースを有効にするには、アプリケーションを起動する前に次の環境変数を設定します。
export GOOGLE_SDK_PYTHON_TRACING_ENABLED=true
true に設定すると、クライアント ライブラリはグローバルに登録された OpenTelemetry TracerProvider を自動的に検出し、すべてのクライアント呼び出しのスパンを出力します。
オプション 2: クライアントごとの構成(コード)
きめ細かい制御やマルチテナント アプリケーションの場合は、ClientOptions を使用して tracer_provider を渡すことで、特定のクライアント インスタンスを構成します。
from google.api_core.client_options import ClientOptions
from google.cloud import secretmanager
options = ClientOptions(tracer_provider=my_tracer_provider)
client = secretmanager.SecretManagerServiceClient(client_options=options)
サンプルコード
クライアント ライブラリは、アプリケーションのデフォルト認証情報を使用することによって、Google API で簡単に認証を行い、これらの API にリクエストを送信できます。アプリケーションのデフォルト認証情報を使用すると、ベースとなるコードを変更することなく、ローカルでアプリケーションのテストを行ったり、アプリケーションをデプロイしたりできます。詳細については、クライアント ライブラリを使用するための認証をご覧ください。
1. クイックスタートの例(SecretManagerServiceClient)
次の自己完結型の例は、標準の OpenTelemetry を構成し、環境変数を使用してクライアント ライブラリのトレースを有効にし、ConsoleSpanExporter を使用して出力されたスパンを JSON としてターミナルに直接出力する方法を示しています。
import os from google.cloud import secretmanager from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor def get_secret_version_with_tracing( project_id: str, secret_id: str, version_id: str = "latest", ) -> secretmanager.SecretVersion: """Get a secret version in Secret Manager with OpenTelemetry tracing enabled. Args: project_id: Google Cloud project ID. secret_id: ID of the secret. version_id: ID of the secret version (defaults to "latest"). Returns: The SecretVersion metadata object. """ # NOTE: In standalone scripts or CLI tools, initialize and shut down the # TracerProvider within the script workflow. In long-running production # applications (e.g., web servers), configure the TracerProvider once at # application startup. # # Initialize the OpenTelemetry TracerProvider with a Console exporter provider = TracerProvider() provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter())) trace.set_tracer_provider(provider) # Enable Google Cloud client library tracing os.environ["GOOGLE_SDK_PYTHON_TRACING_ENABLED"] = "true" # Instantiate the client (automatically discovers the active TracerProvider) client = secretmanager.SecretManagerServiceClient() # Construct the resource name and invoke the RPC name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" try: print("--- OpenTelemetry Trace Spans (JSON) ---") response = client.get_secret_version(request={"name": name}) state_name = response.state.name print( f"\nAPI Result: Retrieved secret version {response.name} (state: {state_name})" ) return response finally: # Flush buffered spans before program completion provider.shutdown()
2. プログラマティック構成(ClientOptions)
環境変数を使用しない場合や、異なる TracerProvider インスタンスを異なるクライアントに渡す必要がある場合は、ClientOptions を使用して tracer_provider を渡すことで、クライアントをプログラムで構成します。
from google.api_core.client_options import ClientOptions from google.cloud import secretmanager from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor def get_secret_version_with_client_options( project_id: str, secret_id: str, version_id: str = "latest", ) -> secretmanager.SecretVersion: """Get a secret version configuring tracing programmatically via ClientOptions. Args: project_id: Google Cloud project ID. secret_id: ID of the secret. version_id: ID of the secret version (defaults to "latest"). Returns: The SecretVersion metadata object. """ # Initialize an independent TracerProvider (no global registration required) provider = TracerProvider() provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter())) # Pass the TracerProvider directly via ClientOptions # Tracing is activated specifically for this client instance, even without # setting the GOOGLE_SDK_PYTHON_TRACING_ENABLED environment variable. options = ClientOptions(tracer_provider=provider) client = secretmanager.SecretManagerServiceClient(client_options=options) # Construct resource name and invoke RPC name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" try: print("--- OpenTelemetry Trace Spans (JSON) ---") response = client.get_secret_version(request={"name": name}) state_name = response.state.name print( f"\nAPI Result: Retrieved secret version {response.name} (state: {state_name})" ) return response finally: # Flush buffered spans before program completion provider.shutdown()
3. 非同期クライアントの例(SecretManagerServiceAsyncClient)
次のサンプルでは、SecretManagerServiceAsyncClient を使用して非同期コルーチン(async def get_secret_version_with_tracing_async)を定義しています。このクライアントは非同期であるため、アクティブな asyncio イベントループ内で実行してください。
import asyncio import os from google.cloud import secretmanager from opentelemetry import trace from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor async def get_secret_version_with_tracing_async( project_id: str, secret_id: str, version_id: str = "latest", ) -> secretmanager.SecretVersion: """Get a secret version using SecretManagerServiceAsyncClient with OpenTelemetry tracing. Args: project_id: Google Cloud project ID. secret_id: ID of the secret. version_id: ID of the secret version (defaults to "latest"). Returns: The SecretVersion metadata object. """ # NOTE: In standalone scripts or CLI tools, initialize and shut down the # TracerProvider within the script workflow. In long-running production # applications (e.g., web servers), configure the TracerProvider once at # application startup. # # Initialize the OpenTelemetry TracerProvider with a Console exporter provider = TracerProvider() provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter())) trace.set_tracer_provider(provider) # Enable Google Cloud client library tracing os.environ["GOOGLE_SDK_PYTHON_TRACING_ENABLED"] = "true" # Instantiate the async client client = secretmanager.SecretManagerServiceAsyncClient() # Construct resource name and invoke the async RPC name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}" try: print("--- OpenTelemetry Trace Spans (JSON) ---") response = await client.get_secret_version(request={"name": name}) state_name = response.state.name print( f"\nAPI Result: Retrieved secret version {response.name} (state: {state_name})" ) return response finally: # Flush buffered spans before program completion provider.shutdown()
セマンティック属性リファレンス
Cloud de Confiance by S3NS Python クライアント ライブラリから出力されるスパンは、標準の RPC スパンの OpenTelemetry セマンティック規則に準拠しており、トランスポート プロトコル、RPC メソッド ID、宛先サーバー アドレス、レスポンス ステータス コード、エラーの詳細に関する標準メタデータを記録します。これらの属性を使用して、オブザーバビリティ ダッシュボードまたは Cloud Trace ダッシュボードでフィルタ、集計、アラート ポリシーの作成を行うことができます。
セキュリティと機密データ
Cloud de Confiance by S3NS Python クライアント ライブラリのインストルメンテーションは、厳格なセキュリティ基準とプライバシー基準に準拠するように設計されています。
- ペイロード保護: クライアント ライブラリは、リクエストまたはレスポンスのペイロード データ(ファイルの内容、シークレット値、データベース クエリの結果など)をトレーススパンに記録しません。
- 識別子の可視性: リソース名(プロジェクト ID、データセット ID、シークレット名など)は、メソッド パラメータと URL エンドポイント属性に表示されます。リソース ID に機密性の高いビジネス情報が含まれている場合は、トレース ストレージが内部コンプライアンス ポリシーに準拠していることを確認してください。
- サードパーティのエクスポータ: トレースをサードパーティのオブザーバビリティ サービスまたは SaaS ベンダーにエクスポートする場合は、組織のデータ保護契約を確認し、必要に応じてエクスポータ属性フィルタリングを構成します。