Ensuring the health and availability of your Firestore database is crucial for maintaining a reliable application. This post provides a Python script that serves as an uptime check, leveraging the Firestore Admin API to determine the database’s status.

Firestore Health Check Script

Below is a Python script designed to check the health and availability of a Google Cloud Firestore database. It uses the Firestore Admin API to query the status of a specific database instance.

import os
import sys
from google.cloud import firestore_admin_v1
from google.api_core import exceptions

def check_firestore_health():
    """
    Checks the health of a live Firestore instance using the Admin API.
    This is suitable for uptime checks.
    
    Expects the GOOGLE_CLOUD_PROJECT environment variable to be set.
    Authentication is handled by the Google Cloud client library, typically via
    Application Default Credentials (ADC).

    Exits with code 0 on success and 1 on failure.
    """
    try:
        # --- Configuration ---
        # Get the project ID from an environment variable.
        project_id = os.environ.get('GOOGLE_CLOUD_PROJECT')
        if not project_id:
            print("Error: GOOGLE_CLOUD_PROJECT environment variable is not set.", file=sys.stderr)
            sys.exit(1)

        # The database ID for the default database is '(default)'.
        database_id = '(default)'
        
        # The resource name is formatted as projects/{project_id}/databases/{database_id}
        database_name = f"projects/{project_id}/databases/{database_id}"

        # --- Health Check ---
        # Create a Firestore Admin client.
        # The client will use Application Default Credentials for authentication.
        # Ensure you have authenticated via `gcloud auth application-default login`
        # or have the GOOGLE_APPLICATION_CREDENTIALS environment variable set.
        client = firestore_admin_v1.FirestoreAdminClient()

        # Initialize the request to get database details
        request = firestore_admin_v1.GetDatabaseRequest(
            name=database_name,
        )

        # Make the API request
        print(f"Checking status of Firestore database '{database_name}'...")
        response = client.get_database(request=request)

        # A successful response indicates the database is reachable and the API is healthy.
        # We can perform a more specific check on the database's reported health state.
        if response.health_mode == firestore_admin_v1.Database.HealthMode.HEALTHY:
             print(f"Successfully connected to Firestore. Database state is: {response.health_mode.name}")
             sys.exit(0) # Exit with a success code
        else:
            print(f"Warning: Connected to Firestore, but database state is not HEALTHY. Current state: {response.health_mode.name}", file=sys.stderr)
            sys.exit(1) # Exit with an error code as the database is not healthy

    except exceptions.PermissionDenied as e:
        print(f"Permission denied. Ensure your credentials have the 'datastore.databases.get' permission. Details: {e}", file=sys.stderr)
        sys.exit(1)
    except exceptions.NotFound:
        print(f"Error: The database '{database_name}' was not found. Please check your project ID.", file=sys.stderr)
        sys.exit(1)
    except exceptions.GoogleAPICallError as e:
        # Catch other specific API errors for better diagnostics
        print(f"Failed to query Firestore Admin API: {e}", file=sys.stderr)
        sys.exit(1) # Exit with an error code
    except Exception as e:
        # Catch any other exceptions (e.g., authentication setup issues)
        print(f"An unexpected error occurred: {e}", file=sys.stderr)
        sys.exit(1) # Exit with an error code

if __name__ == "__main__":
    check_firestore_health()

Overview

This Python script is a command-line tool designed to check the health and availability of a Google Cloud Firestore database. It uses the Firestore Admin API to query the status of a specific database instance.

It is intended to be used in automated environments, such as uptime checks, monitoring systems, or within a CI/CD pipeline, as it exits with a status code of 0 for a healthy database and 1 for any failure or non-healthy state.

Prerequisites

  • Python 3.7+
  • Google Cloud SDK (gcloud) installed and configured.
  • A Google Cloud project with the Firestore API enabled.

Setup

1. Install Dependencies

The script requires the google-cloud-firestore-admin library. You can install it using pip:

pip install google-cloud-firestore-admin

2. Authentication

This script uses Application Default Credentials (ADC) for authentication. Before running it, you need to authenticate your environment.

For local development or manual checks:

Run the following command and follow the prompts to log in with your Google Cloud account:

gcloud auth application-default login

For automated environments (e.g., CI/CD, servers):

  1. Create a service account with the Cloud Datastore Viewer role, which includes the datastore.databases.get permission.
  2. Download the JSON key file for this service account.
  3. Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of your key file:
    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/keyfile.json"
    

3. Configure Project ID

The script requires the Google Cloud project ID to be set as an environment variable.

export GOOGLE_CLOUD_PROJECT="your-gcp-project-id"

How to Run

Once the prerequisites, authentication, and configuration are complete, you can run the script directly:

python3 firestore_health_check.py

Important: Save the above Python code to a file named firestore_health_check.py or similar.

Exit Codes & Output

The script provides clear output and uses standard exit codes for automation.

On Success

If the Firestore database is reachable and reported as HEALTHY, the script will print a success message and exit with code 0.

Output:

Checking status of Firestore database 'projects/your-gcp-project-id/databases/(default)'...
Successfully connected to Firestore. Database state is: HEALTHY

On Failure

If there is any issue—such as incorrect configuration, permissions errors, or if the database is not in a HEALTHY state—the script will print an error message to stderr and exit with code 1.

Example Failure Outputs:

  • Environment variable not set:
    Error: GOOGLE_CLOUD_PROJECT environment variable is not set.
    
  • Permission denied:
    Permission denied. Ensure your credentials have the 'datastore.databases.get' permission. Details: 403 Forbidden
    
  • Database not healthy:
    Warning: Connected to Firestore, but database state is not HEALTHY. Current state: DEGRADED
    

Use Cases

  • Uptime Monitoring: Integrate the script with a monitoring service (like Google Cloud Monitoring, Datadog, or a simple cron job) to periodically check Firestore’s availability.
  • CI/CD Pipelines: Use it as a health check step in a deployment pipeline to ensure the database is ready before deploying or running an application.
  • Kubernetes: Configure it as a liveness or readiness probe for applications that depend heavily on Firestore.