Management of job executions and their lifecycle. Executions represent individual runs of a job and contain one or more tasks that process the workload.
Create and configure execution clients for monitoring job runs.
class ExecutionsClient:
"""Synchronous client for managing Cloud Run executions."""
def __init__(self, *, credentials=None, transport=None, client_options=None, client_info=None):
"""
Initialize the Executions client.
Args:
credentials: Optional authentication credentials
transport: Transport to use for requests (grpc, grpc_asyncio, rest)
client_options: Client configuration options
client_info: Client information for user agent
"""
class ExecutionsAsyncClient:
"""Asynchronous client for managing Cloud Run executions."""Get execution details, status, and progress information.
def get_execution(
self,
request: GetExecutionRequest = None,
*,
name: str = None,
**kwargs
) -> Execution:
"""
Get a Cloud Run execution.
Args:
request: The request object
name: Required. The name of the execution. Format: projects/{project}/locations/{location}/jobs/{job}/executions/{execution}
Returns:
Execution: The execution details and status
"""Usage Example:
from google.cloud import run_v2
client = run_v2.ExecutionsClient()
# Get execution details
execution = client.get_execution(
name="projects/my-project/locations/us-central1/jobs/my-job/executions/my-execution-123"
)
print(f"Execution: {execution.name}")
print(f"Status: {execution.status.completion_status}")
print(f"Tasks: {execution.status.task_count} total, {execution.status.succeeded_count} succeeded")
print(f"Started: {execution.status.start_time}")
if execution.status.completion_time:
print(f"Completed: {execution.status.completion_time}")List executions for a job with filtering and pagination.
def list_executions(
self,
request: ListExecutionsRequest = None,
*,
parent: str = None,
**kwargs
) -> ListExecutionsResponse:
"""
List Cloud Run executions for a job.
Args:
request: The request object
parent: Required. The job to list executions for. Format: projects/{project}/locations/{location}/jobs/{job}
Returns:
ListExecutionsResponse: Paginated list of executions
"""Usage Example:
# List all executions for a job
request = run_v2.ListExecutionsRequest(
parent="projects/my-project/locations/us-central1/jobs/my-batch-job"
)
page_result = client.list_executions(request=request)
for execution in page_result:
print(f"Execution: {execution.name}")
print(f" Status: {execution.status.completion_status}")
print(f" Started: {execution.status.start_time}")
print(f" Tasks: {execution.status.succeeded_count}/{execution.status.task_count}")Cancel running executions to stop processing.
def cancel_execution(
self,
request: CancelExecutionRequest = None,
*,
name: str = None,
**kwargs
) -> Operation:
"""
Cancel a Cloud Run execution.
Args:
request: The request object
name: Required. The name of the execution to cancel
Returns:
Operation: Long-running operation for the cancellation
"""Usage Example:
# Cancel a running execution
cancel_request = run_v2.CancelExecutionRequest(
name="projects/my-project/locations/us-central1/jobs/my-job/executions/my-execution-123"
)
operation = client.cancel_execution(request=cancel_request)
result = operation.result()
print(f"Execution cancelled: {result.name}")Delete completed executions to clean up resources.
def delete_execution(
self,
request: DeleteExecutionRequest = None,
*,
name: str = None,
**kwargs
) -> Operation:
"""
Delete a Cloud Run execution.
Args:
request: The request object
name: Required. The name of the execution to delete
Returns:
Operation: Long-running operation for the deletion
"""class Execution:
"""
A Cloud Run execution instance.
Attributes:
name (str): The unique name of the execution
uid (str): Unique identifier assigned by the system
generation (int): A sequence number representing a specific generation
labels (dict): User-defined labels
annotations (dict): User-defined annotations
create_time (Timestamp): The creation time
start_time (Timestamp): When the execution started running
completion_time (Timestamp): When the execution completed
update_time (Timestamp): The last modification time
delete_time (Timestamp): The deletion time
expire_time (Timestamp): When the execution expires
launch_stage (LaunchStage): The launch stage of the execution
job (str): The name of the job that created this execution
parallelism (int): The maximum number of tasks that can run in parallel
task_count (int): The number of tasks in this execution
template (TaskTemplate): The template used to create tasks
reconciling (bool): Whether the execution is currently being reconciled
conditions (list[Condition]): Detailed status conditions
observed_generation (int): The generation observed by the controller
running_count (int): Number of tasks which are currently running
succeeded_count (int): Number of tasks which have completed successfully
failed_count (int): Number of tasks which have failed
cancelled_count (int): Number of tasks which were cancelled
retried_count (int): Number of tasks which have been retried
log_uri (str): URI where logs for this execution can be found
satisfies_pzs (bool): Whether the execution satisfies PZS requirements
etag (str): A fingerprint used for optimistic concurrency control
"""
class ExecutionStatus:
"""
Status information for an execution.
Attributes:
completion_status (CompletionStatus): Overall completion status
start_time (Timestamp): When execution started
completion_time (Timestamp): When execution completed
task_count (int): Total number of tasks
running_count (int): Number of running tasks
succeeded_count (int): Number of succeeded tasks
failed_count (int): Number of failed tasks
cancelled_count (int): Number of cancelled tasks
"""class GetExecutionRequest:
"""
Request message for getting an execution.
Attributes:
name (str): Required. The name of the execution to retrieve
"""
class ListExecutionsRequest:
"""
Request message for listing executions.
Attributes:
parent (str): Required. The job to list executions for
page_size (int): Maximum number of executions to return
page_token (str): Token for retrieving the next page
show_deleted (bool): Whether to include deleted executions
"""
class CancelExecutionRequest:
"""
Request message for cancelling an execution.
Attributes:
name (str): Required. The name of the execution to cancel
validate_only (bool): Indicates whether to validate only
etag (str): A fingerprint for optimistic concurrency control
"""
class DeleteExecutionRequest:
"""
Request message for deleting an execution.
Attributes:
name (str): Required. The name of the execution to delete
validate_only (bool): Indicates whether to validate only
etag (str): A fingerprint for optimistic concurrency control
"""class ListExecutionsResponse:
"""
Response message for listing executions.
Attributes:
executions (list[Execution]): The list of executions
next_page_token (str): Token for retrieving the next page
"""class CompletionStatus:
"""
Completion status of an execution.
Values:
COMPLETION_STATUS_UNSPECIFIED: The default value. This value is used if the status is omitted.
EXECUTION_SUCCEEDED: Job execution has succeeded.
EXECUTION_FAILED: Job execution has failed.
EXECUTION_RUNNING: Job execution is running normally.
EXECUTION_PENDING: Job execution is pending, waiting for resources.
EXECUTION_CANCELLED: Job execution has been cancelled by the user.
"""
COMPLETION_STATUS_UNSPECIFIED = 0
EXECUTION_SUCCEEDED = 1
EXECUTION_FAILED = 2
EXECUTION_RUNNING = 3
EXECUTION_PENDING = 4
EXECUTION_CANCELLED = 5import time
from google.cloud import run_v2
client = run_v2.ExecutionsClient()
def monitor_execution(execution_name):
"""Monitor an execution until completion."""
while True:
execution = client.get_execution(name=execution_name)
status = execution.status.completion_status
print(f"Status: {status}")
print(f"Tasks: {execution.status.succeeded_count}/{execution.status.task_count} completed")
if status in [
run_v2.Execution.CompletionStatus.EXECUTION_SUCCEEDED,
run_v2.Execution.CompletionStatus.EXECUTION_FAILED,
run_v2.Execution.CompletionStatus.EXECUTION_CANCELLED
]:
break
time.sleep(30) # Check every 30 seconds
return execution
# Usage
execution = monitor_execution(
"projects/my-project/locations/us-central1/jobs/my-job/executions/my-execution-123"
)def handle_failed_execution(execution_name):
"""Handle a failed execution by examining tasks."""
execution = client.get_execution(name=execution_name)
if execution.status.completion_status == run_v2.Execution.CompletionStatus.EXECUTION_FAILED:
print(f"Execution failed: {execution.name}")
print(f"Failed tasks: {execution.status.failed_count}")
print(f"Succeeded tasks: {execution.status.succeeded_count}")
# Get detailed task information
tasks_client = run_v2.TasksClient()
tasks_request = run_v2.ListTasksRequest(parent=execution.name)
for task in tasks_client.list_tasks(request=tasks_request):
if task.status.completion_status == run_v2.Task.CompletionStatus.TASK_FAILED:
print(f"Failed task: {task.name}")
print(f"Exit code: {task.status.exit_code}")
print(f"Log URI: {task.log_uri}")def cleanup_old_executions(job_name, days_old=7):
"""Delete executions older than specified days."""
from datetime import datetime, timedelta
request = run_v2.ListExecutionsRequest(parent=job_name)
cutoff_time = datetime.now() - timedelta(days=days_old)
for execution in client.list_executions(request=request):
if execution.completion_time:
completion_time = execution.completion_time.timestamp()
if datetime.fromtimestamp(completion_time) < cutoff_time:
print(f"Deleting old execution: {execution.name}")
delete_request = run_v2.DeleteExecutionRequest(name=execution.name)
client.delete_execution(request=delete_request)