Google Cloud Service Control

1.19.0 · active · verified Fri Apr 17

The `google-cloud-service-control` library is the Python client for the Google Cloud Service Control API, which allows services to report operations and check their status against Google Cloud's managed services. It is part of the larger `google-cloud-python` monorepo, currently at version 1.19.0, and receives frequent updates in line with Google Cloud's API changes and Python ecosystem best practices.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `ServiceControllerClient` and send a `ReportRequest`. It requires setting `SERVICE_NAME` to your managed service name and `CONSUMER_ID` to the Google Cloud project consuming the service. The example creates a basic `Operation` with a log entry and reports it. Ensure `GOOGLE_APPLICATION_CREDENTIALS` is set or default credentials are configured.

import os
from google.cloud import service_control_v1
from google.protobuf import timestamp_pb2

# Replace with your actual service name and consumer ID
# The service name must be registered in Google Service Management.
SERVICE_NAME = os.environ.get("GCP_SERVICE_CONTROL_SERVICE_NAME", "my-service.endpoints.project-id.cloud.goog")
CONSUMER_ID = os.environ.get("GCP_SERVICE_CONTROL_CONSUMER_ID", "project:your-gcp-project-id") # e.g., 'project:my-project-id'

# Create a client
client = service_control_v1.ServiceControllerClient()

# Prepare an operation
now = timestamp_pb2.Timestamp()
now.GetCurrentTime()

operation = service_control_v1.Operation(
    operation_id="test-operation-123",
    consumer_id=CONSUMER_ID,
    start_time=now,
    end_time=now,
    operation_name="example.method",
    user_labels={
        "environment": "dev",
        "component": "example"
    },
    log_entries=[
        service_control_v1.LogEntry(
            name="access_log",
            text_payload="Example log message from service control."
        )
    ]
)

# Create a ReportRequest
request = service_control_v1.ReportRequest(
    service_name=SERVICE_NAME,
    operations=[operation],
)

try:
    # Send the report
    response = client.report(request=request)
    print(f"Report successful. Processed operations: {len(response.report_errors)}")
    if response.report_errors:
        for error in response.report_errors:
            print(f"  Error for operation '{error.operation_id}': {error.code} - {error.message}")
except Exception as e:
    print(f"An error occurred during reporting: {e}")

view raw JSON →