|
| 1 | +# Copyright 2020 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""This application demonstrates how to create and restore from backups |
| 16 | +using Cloud Spanner. |
| 17 | +
|
| 18 | +For more information, see the README.rst under /spanner. |
| 19 | +""" |
| 20 | + |
| 21 | +import argparse |
| 22 | +from datetime import datetime, timedelta |
| 23 | +import time |
| 24 | + |
| 25 | +from google.cloud import spanner |
| 26 | + |
| 27 | + |
| 28 | +# [START spanner_create_backup] |
| 29 | +def create_backup(instance_id, database_id, backup_id): |
| 30 | + """Creates a backup for a database.""" |
| 31 | + spanner_client = spanner.Client() |
| 32 | + instance = spanner_client.instance(instance_id) |
| 33 | + database = instance.database(database_id) |
| 34 | + |
| 35 | + # Create a backup |
| 36 | + expire_time = datetime.utcnow() + timedelta(days=14) |
| 37 | + backup = instance.backup(backup_id, database=database, expire_time=expire_time) |
| 38 | + operation = backup.create() |
| 39 | + |
| 40 | + # Wait for backup operation to complete. |
| 41 | + operation.result(1200) |
| 42 | + |
| 43 | + # Verify that the backup is ready. |
| 44 | + backup.reload() |
| 45 | + assert backup.is_ready() is True |
| 46 | + |
| 47 | + # Get the name, create time and backup size. |
| 48 | + backup.reload() |
| 49 | + print( |
| 50 | + "Backup {} of size {} bytes was created at {}".format( |
| 51 | + backup.name, backup.size_bytes, backup.create_time |
| 52 | + ) |
| 53 | + ) |
| 54 | + |
| 55 | + |
| 56 | +# [END spanner_create_backup] |
| 57 | + |
| 58 | + |
| 59 | +# [START spanner_restore_database] |
| 60 | +def restore_database(instance_id, new_database_id, backup_id): |
| 61 | + """Restores a database from a backup.""" |
| 62 | + spanner_client = spanner.Client() |
| 63 | + instance = spanner_client.instance(instance_id) |
| 64 | + # Create a backup on database_id. |
| 65 | + |
| 66 | + # Start restoring backup to a new database. |
| 67 | + backup = instance.backup(backup_id) |
| 68 | + new_database = instance.database(new_database_id) |
| 69 | + operation = new_database.restore(backup) |
| 70 | + |
| 71 | + # Wait for restore operation to complete. |
| 72 | + operation.result(1200) |
| 73 | + |
| 74 | + # Newly created database has restore information. |
| 75 | + new_database.reload() |
| 76 | + restore_info = new_database.restore_info |
| 77 | + print( |
| 78 | + "Database {} restored to {} from backup {}.".format( |
| 79 | + restore_info.backup_info.source_database, |
| 80 | + new_database_id, |
| 81 | + restore_info.backup_info.backup, |
| 82 | + ) |
| 83 | + ) |
| 84 | + |
| 85 | + |
| 86 | +# [END spanner_restore_database] |
| 87 | + |
| 88 | + |
| 89 | +# [START spanner_cancel_backup] |
| 90 | +def cancel_backup(instance_id, database_id, backup_id): |
| 91 | + spanner_client = spanner.Client() |
| 92 | + instance = spanner_client.instance(instance_id) |
| 93 | + database = instance.database(database_id) |
| 94 | + |
| 95 | + expire_time = datetime.utcnow() + timedelta(days=30) |
| 96 | + |
| 97 | + # Create a backup. |
| 98 | + backup = instance.backup(backup_id, database=database, expire_time=expire_time) |
| 99 | + operation = backup.create() |
| 100 | + |
| 101 | + # Cancel backup creation. |
| 102 | + operation.cancel() |
| 103 | + |
| 104 | + # Cancel operations are best effort so either it will complete or |
| 105 | + # be cancelled. |
| 106 | + while not operation.done(): |
| 107 | + time.sleep(300) # 5 mins |
| 108 | + |
| 109 | + # Deal with resource if the operation succeeded. |
| 110 | + if backup.exists(): |
| 111 | + print("Backup was created before the cancel completed.") |
| 112 | + backup.delete() |
| 113 | + print("Backup deleted.") |
| 114 | + else: |
| 115 | + print("Backup creation was successfully cancelled.") |
| 116 | + |
| 117 | + |
| 118 | +# [END spanner_cancel_backup] |
| 119 | + |
| 120 | + |
| 121 | +# [START spanner_list_backup_operations] |
| 122 | +def list_backup_operations(instance_id, database_id): |
| 123 | + spanner_client = spanner.Client() |
| 124 | + instance = spanner_client.instance(instance_id) |
| 125 | + |
| 126 | + # List the CreateBackup operations. |
| 127 | + filter_ = ( |
| 128 | + "(metadata.database:{}) AND " |
| 129 | + "(metadata.@type:type.googleapis.com/" |
| 130 | + "google.spanner.admin.database.v1.CreateBackupMetadata)" |
| 131 | + ).format(database_id) |
| 132 | + operations = instance.list_backup_operations(filter_=filter_) |
| 133 | + for op in operations: |
| 134 | + metadata = op.metadata |
| 135 | + print( |
| 136 | + "Backup {} on database {}: {}% complete.".format( |
| 137 | + metadata.name, metadata.database, metadata.progress.progress_percent |
| 138 | + ) |
| 139 | + ) |
| 140 | + |
| 141 | + |
| 142 | +# [END spanner_list_backup_operations] |
| 143 | + |
| 144 | + |
| 145 | +# [START spanner_list_database_operations] |
| 146 | +def list_database_operations(instance_id): |
| 147 | + spanner_client = spanner.Client() |
| 148 | + instance = spanner_client.instance(instance_id) |
| 149 | + |
| 150 | + # List the progress of restore. |
| 151 | + filter_ = ( |
| 152 | + "(metadata.@type:type.googleapis.com/" |
| 153 | + "google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)" |
| 154 | + ) |
| 155 | + operations = instance.list_database_operations(filter_=filter_) |
| 156 | + for op in operations: |
| 157 | + print( |
| 158 | + "Database {} restored from backup is {}% optimized.".format( |
| 159 | + op.metadata.name, op.metadata.progress.progress_percent |
| 160 | + ) |
| 161 | + ) |
| 162 | + |
| 163 | + |
| 164 | +# [END spanner_list_database_operations] |
| 165 | + |
| 166 | + |
| 167 | +# [START spanner_list_backups] |
| 168 | +def list_backups(instance_id, database_id, backup_id): |
| 169 | + spanner_client = spanner.Client() |
| 170 | + instance = spanner_client.instance(instance_id) |
| 171 | + |
| 172 | + # List all backups. |
| 173 | + print("All backups:") |
| 174 | + for backup in instance.list_backups(): |
| 175 | + print(backup.name) |
| 176 | + |
| 177 | + # List all backups that contain a name. |
| 178 | + print('All backups with backup name containing "{}":'.format(backup_id)) |
| 179 | + for backup in instance.list_backups(filter_="name:{}".format(backup_id)): |
| 180 | + print(backup.name) |
| 181 | + |
| 182 | + # List all backups for a database that contains a name. |
| 183 | + print('All backups with database name containing "{}":'.format(database_id)) |
| 184 | + for backup in instance.list_backups(filter_="database:{}".format(database_id)): |
| 185 | + print(backup.name) |
| 186 | + |
| 187 | + # List all backups that expire before a timestamp. |
| 188 | + expire_time = datetime.utcnow().replace(microsecond=0) + timedelta(days=30) |
| 189 | + print( |
| 190 | + 'All backups with expire_time before "{}-{}-{}T{}:{}:{}Z":'.format( |
| 191 | + *expire_time.timetuple() |
| 192 | + ) |
| 193 | + ) |
| 194 | + for backup in instance.list_backups( |
| 195 | + filter_='expire_time < "{}-{}-{}T{}:{}:{}Z"'.format(*expire_time.timetuple()) |
| 196 | + ): |
| 197 | + print(backup.name) |
| 198 | + |
| 199 | + # List all backups with a size greater than some bytes. |
| 200 | + print("All backups with backup size more than 100 bytes:") |
| 201 | + for backup in instance.list_backups(filter_="size_bytes > 100"): |
| 202 | + print(backup.name) |
| 203 | + |
| 204 | + # List backups that were created after a timestamp that are also ready. |
| 205 | + create_time = datetime.utcnow().replace(microsecond=0) - timedelta(days=1) |
| 206 | + print( |
| 207 | + 'All backups created after "{}-{}-{}T{}:{}:{}Z" and are READY:'.format( |
| 208 | + *create_time.timetuple() |
| 209 | + ) |
| 210 | + ) |
| 211 | + for backup in instance.list_backups( |
| 212 | + filter_='create_time >= "{}-{}-{}T{}:{}:{}Z" AND state:READY'.format( |
| 213 | + *create_time.timetuple() |
| 214 | + ) |
| 215 | + ): |
| 216 | + print(backup.name) |
| 217 | + |
| 218 | + print("All backups with pagination") |
| 219 | + for page in instance.list_backups(page_size=2).pages: |
| 220 | + for backup in page: |
| 221 | + print(backup.name) |
| 222 | + |
| 223 | + |
| 224 | +# [END spanner_list_backups] |
| 225 | + |
| 226 | + |
| 227 | +# [START spanner_delete_backup] |
| 228 | +def delete_backup(instance_id, backup_id): |
| 229 | + spanner_client = spanner.Client() |
| 230 | + instance = spanner_client.instance(instance_id) |
| 231 | + backup = instance.backup(backup_id) |
| 232 | + backup.reload() |
| 233 | + |
| 234 | + # Wait for databases that reference this backup to finish optimizing. |
| 235 | + while backup.referencing_databases: |
| 236 | + time.sleep(30) |
| 237 | + backup.reload() |
| 238 | + |
| 239 | + # Delete the backup. |
| 240 | + backup.delete() |
| 241 | + |
| 242 | + # Verify that the backup is deleted. |
| 243 | + assert backup.exists() is False |
| 244 | + print("Backup {} has been deleted.".format(backup.name)) |
| 245 | + |
| 246 | + |
| 247 | +# [END spanner_delete_backup] |
| 248 | + |
| 249 | + |
| 250 | +# [START spanner_update_backup] |
| 251 | +def update_backup(instance_id, backup_id): |
| 252 | + spanner_client = spanner.Client() |
| 253 | + instance = spanner_client.instance(instance_id) |
| 254 | + backup = instance.backup(backup_id) |
| 255 | + backup.reload() |
| 256 | + |
| 257 | + # Expire time must be within 366 days of the create time of the backup. |
| 258 | + old_expire_time = backup.expire_time |
| 259 | + new_expire_time = old_expire_time + timedelta(days=30) |
| 260 | + backup.update_expire_time(new_expire_time) |
| 261 | + print( |
| 262 | + "Backup {} expire time was updated from {} to {}.".format( |
| 263 | + backup.name, old_expire_time, new_expire_time |
| 264 | + ) |
| 265 | + ) |
| 266 | + |
| 267 | + |
| 268 | +# [END spanner_update_backup] |
| 269 | + |
| 270 | + |
| 271 | +if __name__ == "__main__": # noqa: C901 |
| 272 | + parser = argparse.ArgumentParser( |
| 273 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 274 | + ) |
| 275 | + parser.add_argument("instance_id", help="Your Cloud Spanner instance ID.") |
| 276 | + parser.add_argument( |
| 277 | + "--database-id", help="Your Cloud Spanner database ID.", default="example_db" |
| 278 | + ) |
| 279 | + parser.add_argument( |
| 280 | + "--backup-id", help="Your Cloud Spanner backup ID.", default="example_backup" |
| 281 | + ) |
| 282 | + |
| 283 | + subparsers = parser.add_subparsers(dest="command") |
| 284 | + subparsers.add_parser("create_backup", help=create_backup.__doc__) |
| 285 | + subparsers.add_parser("cancel_backup", help=cancel_backup.__doc__) |
| 286 | + subparsers.add_parser("update_backup", help=update_backup.__doc__) |
| 287 | + subparsers.add_parser("restore_database", help=restore_database.__doc__) |
| 288 | + subparsers.add_parser("list_backups", help=list_backups.__doc__) |
| 289 | + subparsers.add_parser("list_backup_operations", help=list_backup_operations.__doc__) |
| 290 | + subparsers.add_parser( |
| 291 | + "list_database_operations", help=list_database_operations.__doc__ |
| 292 | + ) |
| 293 | + subparsers.add_parser("delete_backup", help=delete_backup.__doc__) |
| 294 | + |
| 295 | + args = parser.parse_args() |
| 296 | + |
| 297 | + if args.command == "create_backup": |
| 298 | + create_backup(args.instance_id, args.database_id, args.backup_id) |
| 299 | + elif args.command == "cancel_backup": |
| 300 | + cancel_backup(args.instance_id, args.database_id, args.backup_id) |
| 301 | + elif args.command == "update_backup": |
| 302 | + update_backup(args.instance_id, args.backup_id) |
| 303 | + elif args.command == "restore_database": |
| 304 | + restore_database(args.instance_id, args.database_id, args.backup_id) |
| 305 | + elif args.command == "list_backups": |
| 306 | + list_backups(args.instance_id, args.database_id, args.backup_id) |
| 307 | + elif args.command == "list_backup_operations": |
| 308 | + list_backup_operations(args.instance_id, args.database_id) |
| 309 | + elif args.command == "list_database_operations": |
| 310 | + list_database_operations(args.instance_id) |
| 311 | + elif args.command == "delete_backup": |
| 312 | + delete_backup(args.instance_id, args.backup_id) |
| 313 | + else: |
| 314 | + print("Command {} did not match expected commands.".format(args.command)) |
0 commit comments