Google Cloud Redis API client library for managing fully managed Redis instances on Google Cloud
—
Advanced instance management including maintenance scheduling, failover operations, Redis version upgrades, and authentication.
Upgrade a Redis instance to a newer Redis version.
def upgrade_instance(
self,
*,
name: str,
redis_version: str,
**kwargs
) -> operation.Operation:
"""
Upgrade a Redis instance to a newer Redis version.
Args:
name: Required. Redis instance resource name using the form:
"projects/{project_id}/locations/{location_id}/instances/{instance_id}"
redis_version: Required. Specifies the target version of Redis to upgrade to.
Format: "REDIS_X_Y" (e.g., "REDIS_6_X", "REDIS_7_X")
Returns:
google.api_core.operation.Operation: A long-running operation object.
The result will be an Instance object.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request failed.
google.api_core.exceptions.NotFound: If the instance doesn't exist.
google.api_core.exceptions.InvalidArgument: If the version is invalid.
"""Initiate a manual failover of a Redis instance to its replica.
def failover_instance(
self,
*,
name: str,
data_protection_mode: Optional[
cloud_redis.FailoverInstanceRequest.DataProtectionMode
] = cloud_redis.FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS,
**kwargs
) -> operation.Operation:
"""
Initiates a failover of the primary node to current replica node for a specific STANDARD_HA Redis instance.
Args:
name: Required. Redis instance resource name using the form:
"projects/{project_id}/locations/{location_id}/instances/{instance_id}"
data_protection_mode: Optional. Specifies different modes of operation for failover.
Defaults to LIMITED_DATA_LOSS.
Returns:
google.api_core.operation.Operation: A long-running operation object.
The result will be an Instance object.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request failed.
google.api_core.exceptions.NotFound: If the instance doesn't exist.
google.api_core.exceptions.FailedPrecondition: If instance is not STANDARD_HA tier.
"""Get the AUTH string for connecting to a Redis instance with authentication enabled.
def get_instance_auth_string(
self, *, name: str, **kwargs
) -> cloud_redis.InstanceAuthString:
"""
Gets the AUTH string for a Redis instance with AUTH enabled.
Args:
name: Required. Redis instance resource name using the form:
"projects/{project_id}/locations/{location_id}/instances/{instance_id}"
Returns:
cloud_redis.InstanceAuthString: The auth string for the instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request failed.
google.api_core.exceptions.NotFound: If the instance doesn't exist.
google.api_core.exceptions.FailedPrecondition: If AUTH is not enabled.
"""Reschedule upcoming maintenance for a Redis instance.
def reschedule_maintenance(
self,
*,
name: str,
reschedule_type: cloud_redis.RescheduleMaintenanceRequest.RescheduleType,
schedule_time: Optional[timestamp_pb2.Timestamp] = None,
**kwargs
) -> operation.Operation:
"""
Reschedule upcoming maintenance of a Redis instance.
Args:
name: Required. Redis instance resource name using the form:
"projects/{project_id}/locations/{location_id}/instances/{instance_id}"
reschedule_type: Required. If reschedule type is SPECIFIC_TIME, then schedule_time is required.
schedule_time: Optional. Timestamp when the maintenance shall be rescheduled to.
Required if reschedule_type is SPECIFIC_TIME.
Returns:
google.api_core.operation.Operation: A long-running operation object.
The result will be an Instance object.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request failed.
google.api_core.exceptions.NotFound: If the instance doesn't exist.
google.api_core.exceptions.InvalidArgument: If schedule_time is invalid.
"""class UpgradeInstanceRequest:
name: str
redis_version: strclass FailoverInstanceRequest:
name: str
data_protection_mode: FailoverInstanceRequest.DataProtectionMode
class FailoverInstanceRequest.DataProtectionMode(Enum):
DATA_PROTECTION_MODE_UNSPECIFIED = 0
LIMITED_DATA_LOSS = 1
FORCE_DATA_LOSS = 2class GetInstanceAuthStringRequest:
name: strclass RescheduleMaintenanceRequest:
name: str
reschedule_type: RescheduleMaintenanceRequest.RescheduleType
schedule_time: Timestamp
class RescheduleMaintenanceRequest.RescheduleType(Enum):
RESCHEDULE_TYPE_UNSPECIFIED = 0
IMMEDIATE = 1
NEXT_AVAILABLE_WINDOW = 2
SPECIFIC_TIME = 3class InstanceAuthString:
auth_string: str
"""The AUTH string for the Redis instance."""from google.cloud.redis import CloudRedisClient
client = CloudRedisClient()
instance_name = "projects/my-project/locations/us-central1/instances/my-redis"
# Check current version and available versions
instance = client.get_instance(name=instance_name)
print(f"Current version: {instance.redis_version}")
print(f"Available versions: {instance.available_maintenance_versions}")
# Upgrade to Redis 7.x
operation = client.upgrade_instance(
name=instance_name,
redis_version="REDIS_7_X"
)
print(f"Upgrade operation started: {operation.name}")
# Wait for upgrade to complete (can take 10-30 minutes)
try:
result = operation.result(timeout=3600) # 1 hour timeout
print(f"Upgrade completed successfully")
print(f"New version: {result.redis_version}")
print(f"Instance state: {result.state}")
except Exception as e:
print(f"Upgrade failed: {e}")from google.cloud.redis import CloudRedisClient, FailoverInstanceRequest
client = CloudRedisClient()
instance_name = "projects/my-project/locations/us-central1/instances/my-ha-redis"
# Check if instance supports failover (must be STANDARD_HA)
instance = client.get_instance(name=instance_name)
if instance.tier != instance.Tier.STANDARD_HA:
print("Failover is only supported for STANDARD_HA instances")
exit(1)
print(f"Current location: {instance.current_location_id}")
print(f"Alternative location: {instance.alternative_location_id}")
# Perform failover with limited data loss protection
operation = client.failover_instance(
name=instance_name,
data_protection_mode=FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS
)
print(f"Failover operation started: {operation.name}")
# Wait for failover to complete
try:
result = operation.result(timeout=1800) # 30 minutes timeout
print(f"Failover completed successfully")
print(f"New primary location: {result.current_location_id}")
except Exception as e:
print(f"Failover failed: {e}")from google.cloud.redis import CloudRedisClient
client = CloudRedisClient()
instance_name = "projects/my-project/locations/us-central1/instances/my-secure-redis"
# Check if AUTH is enabled
instance = client.get_instance(name=instance_name)
if not instance.auth_enabled:
print("AUTH is not enabled for this instance")
exit(1)
# Get the AUTH string
try:
auth_info = client.get_instance_auth_string(name=instance_name)
auth_string = auth_info.auth_string
print(f"AUTH string retrieved successfully")
print(f"Use this string to authenticate: {auth_string}")
# Example connection with AUTH
print(f"\nConnection example:")
print(f"redis-cli -h {instance.host} -p {instance.port} -a {auth_string}")
except Exception as e:
print(f"Failed to get AUTH string: {e}")from google.cloud.redis import CloudRedisClient, RescheduleMaintenanceRequest
from google.protobuf.timestamp_pb2 import Timestamp
from datetime import datetime, timedelta
client = CloudRedisClient()
instance_name = "projects/my-project/locations/us-central1/instances/my-redis"
# Check current maintenance schedule
instance = client.get_instance(name=instance_name)
if instance.maintenance_schedule:
schedule = instance.maintenance_schedule
print(f"Current maintenance scheduled for: {schedule.start_time}")
print(f"Can reschedule: {schedule.can_reschedule}")
if not schedule.can_reschedule:
print("Maintenance cannot be rescheduled")
exit(1)
else:
print("No maintenance currently scheduled")
exit(1)
# Option 1: Reschedule to next available window
operation = client.reschedule_maintenance(
name=instance_name,
reschedule_type=RescheduleMaintenanceRequest.RescheduleType.NEXT_AVAILABLE_WINDOW
)
print(f"Rescheduling to next available window: {operation.name}")
# Option 2: Reschedule to specific time (uncomment to use)
# future_time = datetime.now() + timedelta(days=7) # 1 week from now
# schedule_timestamp = Timestamp()
# schedule_timestamp.FromDatetime(future_time)
#
# operation = client.reschedule_maintenance(
# name=instance_name,
# reschedule_type=RescheduleMaintenanceRequest.RescheduleType.SPECIFIC_TIME,
# schedule_time=schedule_timestamp
# )
# Wait for reschedule operation
try:
result = operation.result(timeout=300) # 5 minutes timeout
print(f"Maintenance rescheduled successfully")
if result.maintenance_schedule:
new_schedule = result.maintenance_schedule
print(f"New maintenance time: {new_schedule.start_time}")
except Exception as e:
print(f"Failed to reschedule maintenance: {e}")from google.cloud.redis import CloudRedisClient
import time
def monitor_instance_health(instance_name: str, check_interval: int = 60):
"""Monitor Redis instance health and maintenance status."""
client = CloudRedisClient()
print(f"Monitoring instance: {instance_name}")
print(f"Check interval: {check_interval} seconds")
print("-" * 50)
while True:
try:
instance = client.get_instance(name=instance_name)
print(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"State: {instance.state}")
print(f"Current Location: {instance.current_location_id}")
if instance.status_message:
print(f"Status: {instance.status_message}")
# Check maintenance schedule
if instance.maintenance_schedule:
schedule = instance.maintenance_schedule
print(f"Maintenance: {schedule.start_time} - {schedule.end_time}")
print(f"Can reschedule: {schedule.can_reschedule}")
# Check for suspension reasons
if instance.suspension_reasons:
print(f"Suspension reasons: {instance.suspension_reasons}")
print("-" * 50)
# Alert on critical states
if instance.state in [instance.State.REPAIRING, instance.State.MAINTENANCE]:
print(f"ALERT: Instance in {instance.state} state")
elif instance.suspension_reasons:
print(f"ALERT: Instance suspended - {instance.suspension_reasons}")
time.sleep(check_interval)
except KeyboardInterrupt:
print("Monitoring stopped by user")
break
except Exception as e:
print(f"Error monitoring instance: {e}")
time.sleep(check_interval)
# Start monitoring
instance_name = "projects/my-project/locations/us-central1/instances/production-redis"
monitor_instance_health(instance_name, check_interval=120) # Check every 2 minutesfrom google.cloud.redis import CloudRedisClient, FailoverInstanceRequest
def emergency_failover(instance_name: str, force: bool = False):
"""Perform emergency failover with data loss protection options."""
client = CloudRedisClient()
try:
# Get current instance state
instance = client.get_instance(name=instance_name)
if instance.tier != instance.Tier.STANDARD_HA:
raise ValueError("Emergency failover only available for STANDARD_HA instances")
if instance.state != instance.State.READY:
print(f"WARNING: Instance state is {instance.state}, not READY")
print(f"Current primary: {instance.current_location_id}")
print(f"Failover target: {instance.alternative_location_id}")
# Choose data protection mode
if force:
data_protection_mode = FailoverInstanceRequest.DataProtectionMode.FORCE_DATA_LOSS
print("WARNING: Forcing failover - potential data loss!")
else:
data_protection_mode = FailoverInstanceRequest.DataProtectionMode.LIMITED_DATA_LOSS
print("Using limited data loss protection")
# Confirm before proceeding
if not force:
confirm = input("Proceed with failover? (yes/no): ")
if confirm.lower() != 'yes':
print("Failover cancelled")
return
# Start failover
operation = client.failover_instance(
name=instance_name,
data_protection_mode=data_protection_mode
)
print(f"Emergency failover initiated: {operation.name}")
# Monitor progress
start_time = time.time()
while not operation.done():
elapsed = time.time() - start_time
print(f"Failover in progress... ({elapsed:.0f}s elapsed)")
time.sleep(10)
operation.reload()
# Check result
if operation.error:
print(f"Failover failed: {operation.error}")
else:
result = operation.result()
print(f"Failover completed successfully!")
print(f"New primary location: {result.current_location_id}")
print(f"Instance state: {result.state}")
except Exception as e:
print(f"Emergency failover error: {e}")
# Usage for emergency situations
instance_name = "projects/my-project/locations/us-central1/instances/critical-redis"
# Normal failover with data protection
emergency_failover(instance_name, force=False)
# Force failover (use only in extreme emergencies)
# emergency_failover(instance_name, force=True)def pre_upgrade_checklist(instance_name: str, target_version: str):
"""Perform pre-upgrade validation and preparation."""
client = CloudRedisClient()
print("Pre-upgrade checklist:")
print("-" * 30)
# Get instance details
instance = client.get_instance(name=instance_name)
# Check 1: Instance state
if instance.state != instance.State.READY:
print(f"❌ Instance state: {instance.state} (should be READY)")
return False
print(f"✅ Instance state: {instance.state}")
# Check 2: Available versions
if target_version not in instance.available_maintenance_versions:
print(f"❌ Target version {target_version} not available")
print(f" Available: {instance.available_maintenance_versions}")
return False
print(f"✅ Target version {target_version} is available")
# Check 3: No pending maintenance
if instance.maintenance_schedule:
print(f"⚠️ Maintenance scheduled: {instance.maintenance_schedule.start_time}")
else:
print("✅ No pending maintenance")
# Check 4: Backup recommendation
print("⚠️ Recommendation: Create backup before upgrade")
print("-" * 30)
return True
# Run checklist before upgrade
if pre_upgrade_checklist(instance_name, "REDIS_7_X"):
print("Ready for upgrade!")
else:
print("Resolve issues before upgrading")Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-redis