백업에서 복원

이 페이지에서는 Spanner 복원 작업과 데이터베이스 복원 방법에 대해 설명합니다. Spanner에서 데이터베이스 복원에 대한 자세한 내용은 복원 개요를 참조하세요.

다음을 사용해서 Spanner 데이터베이스를 복원할 수 있습니다.

  • Google Cloud 콘솔 사용
  • Google Cloud CLI 사용
  • 클라이언트 라이브러리 사용
  • REST 또는 RPC API 사용

시작하기 전에

  • 이 페이지의 gcloud CLI 예시에서는 다음 가정이 사용됩니다.

    • gcloud CLI가 이미 Spanner에 사용하도록 설정되어 있습니다. Spanner에서 Google Cloud CLI를 처음 사용하는 경우 Google Cloud CLI를 사용하여 Spanner 시작하기를 참조하세요.
    • Google Cloud CLI가 자신의 프로젝트에 구성되어 있습니다. 예를 들면 다음과 같습니다.

      gcloud config set core/project PROJECT_ID
      
    • test-instance라는 인스턴스와 example-db라는 데이터베이스가 있습니다.

  • 백업에서 데이터베이스를 복원하는 데 필요한 권한을 얻으려면 관리자에게 인스턴스에 대한 Cloud Spanner 복원 관리자(roles/spanner.restoreAdmin) IAM 역할을 부여해 달라고 요청하세요.

백업에서 데이터베이스 복원

콘솔

  1. Google Cloud 콘솔에서 Spanner 인스턴스 페이지로 이동합니다.

    Spanner 인스턴스 페이지로 이동

  2. 데이터베이스가 포함된 인스턴스를 클릭하여 개요 페이지를 엽니다.

  3. 데이터베이스를 클릭하여 개요 페이지를 엽니다.

  4. 탐색창에서 백업/복원을 클릭합니다.

  5. 선택한 백업에 대해 작업 버튼을 클릭한 후 복원을 선택합니다.

  6. 양식을 작성하고 복원 버튼을 클릭합니다.

작업 진행 상황을 확인하려면 작업 페이지에 표시된 것처럼 진행률 표시를 확인합니다.

56%로 표시된 진행률 표시기 스크린샷

작업에 시간이 너무 오래 걸리는 경우 취소할 수 있습니다. 자세한 내용은 장기 실행 인스턴스 작업 취소를 참조하세요.

gcloud

데이터베이스를 복원하려면 gcloud spanner databases restore를 사용합니다.

gcloud spanner databases restore --async \
  --destination-instance=test-instance --destination-database=example-db-restored \
  --source-instance=test-instance --source-backup=example-db-backup-6

사용 참고사항:

  • 이 명령어는 --async 플래그로 인해 즉시 반환합니다. 이 플래그가 없으면 복원 작업이 완료될 때까지 명령어가 대기합니다.
  • 소스 및 대상 인스턴스가 서로 다르면 동일한 인스턴스 구성을 포함해야 합니다.
  • 대상 데이터베이스가 이미 있으면 작업이 실패합니다.

클라이언트 라이브러리

다음 코드 샘플은 특정 백업에서 데이터베이스를 복원하고 복원 작업(RestoreDatabaseMetadata를 사용하는 작업)이 완료될 때까지 기다립니다. 복원된 데이터베이스는 백업과 동일한 인스턴스에서 생성됩니다. 완료되면 샘플은 데이터베이스에서 일부 복원 정보를 검색 및 출력합니다.

C++

void RestoreDatabase(google::cloud::spanner_admin::DatabaseAdminClient client,
                     std::string const& project_id,
                     std::string const& instance_id,
                     std::string const& database_id,
                     std::string const& backup_id) {
  google::cloud::spanner::Database database(project_id, instance_id,
                                            database_id);
  google::cloud::spanner::Backup backup(database.instance(), backup_id);
  auto restored_db =
      client
          .RestoreDatabase(database.instance().FullName(),
                           database.database_id(), backup.FullName())
          .get();
  if (!restored_db) throw std::move(restored_db).status();
  std::cout << "Database";
  if (restored_db->restore_info().source_type() ==
      google::spanner::admin::database::v1::BACKUP) {
    auto const& backup_info = restored_db->restore_info().backup_info();
    std::cout << " " << backup_info.source_database() << " as of "
              << google::cloud::spanner::MakeTimestamp(
                     backup_info.version_time())
                     .value();
  }
  std::cout << " restored to " << restored_db->name();
  std::cout << " from backup " << backup.FullName();
  std::cout << ".\n";
}

C#


using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.LongRunning;
using System;

public class RestoreDatabaseSample
{
    public RestoreInfo RestoreDatabase(string projectId, string instanceId, string databaseId, string backupId)
    {
        // Create the DatabaseAdminClient instance.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

        InstanceName parentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId);
        BackupName backupAsBackupName = BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);

        // Make the RestoreDatabase request.
        Operation<Database, RestoreDatabaseMetadata> response = databaseAdminClient.RestoreDatabase(parentAsInstanceName, databaseId, backupAsBackupName);

        Console.WriteLine("Waiting for the operation to finish");

        // Poll until the returned long-running operation is complete.
        var completedResponse = response.PollUntilCompleted();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Database Restore Failed: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        RestoreInfo restoreInfo = completedResponse.Result.RestoreInfo;
        Console.WriteLine(
            $"Database {restoreInfo.BackupInfo.SourceDatabase} was restored " +
            $"to {databaseId} from backup {restoreInfo.BackupInfo.Backup} " +
            $"with version time {restoreInfo.BackupInfo.VersionTime.ToDateTime()}");

        return restoreInfo;
    }
}

Go


import (
	"context"
	"fmt"
	"io"
	"regexp"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"
)

func restoreBackup(ctx context.Context, w io.Writer, db, backupID string) error {
	adminClient, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()

	matches := regexp.MustCompile("^(.*)/databases/(.*)$").FindStringSubmatch(db)
	if matches == nil || len(matches) != 3 {
		return fmt.Errorf("Invalid database id %s", db)
	}
	instanceName := matches[1]
	databaseID := matches[2]
	backupName := instanceName + "/backups/" + backupID

	// Start restoring backup to a new database.
	restoreOp, err := adminClient.RestoreDatabase(ctx, &adminpb.RestoreDatabaseRequest{
		Parent:     instanceName,
		DatabaseId: databaseID,
		Source: &adminpb.RestoreDatabaseRequest_Backup{
			Backup: backupName,
		},
	})
	if err != nil {
		return err
	}
	// Wait for restore operation to complete.
	dbObj, err := restoreOp.Wait(ctx)
	if err != nil {
		return err
	}
	// Newly created database has restore information.
	backupInfo := dbObj.RestoreInfo.GetBackupInfo()
	if backupInfo != nil {
		fmt.Fprintf(w, "Source database %s restored from backup %s\n", backupInfo.SourceDatabase, backupInfo.Backup)
	}

	return nil
}

자바

static void restoreBackup(
    DatabaseAdminClient dbAdminClient,
    String projectId,
    String instanceId,
    String backupId,
    String restoreToDatabaseId) {
  BackupName backupName = BackupName.of(projectId, instanceId, backupId);
  Backup backup = dbAdminClient.getBackup(backupName);
  // Initiate the request which returns an OperationFuture.
  System.out.println(String.format(
      "Restoring backup [%s] to database [%s]...", backup.getName(), restoreToDatabaseId));
  try {
    RestoreDatabaseRequest request =
        RestoreDatabaseRequest.newBuilder()
            .setParent(InstanceName.of(projectId, instanceId).toString())
            .setDatabaseId(restoreToDatabaseId)
            .setBackup(backupName.toString()).build();
    OperationFuture<com.google.spanner.admin.database.v1.Database, RestoreDatabaseMetadata> op =
        dbAdminClient.restoreDatabaseAsync(request);
    // Wait until the database has been restored.
    com.google.spanner.admin.database.v1.Database db = op.get();
    // Get the restore info.
    RestoreInfo restoreInfo = db.getRestoreInfo();
    BackupInfo backupInfo = restoreInfo.getBackupInfo();

    System.out.println(
        "Restored database ["
            + db.getName()
            + "] from ["
            + restoreInfo.getBackupInfo().getBackup()
            + "] with version time [" + backupInfo.getVersionTime() + "]");
  } catch (ExecutionException e) {
    throw SpannerExceptionFactory.newSpannerException(e.getCause());
  } catch (InterruptedException e) {
    throw SpannerExceptionFactory.propagateInterrupt(e);
  }
}

Node.js

// Imports the Google Cloud client library and precise date library
const {Spanner} = require('@google-cloud/spanner');
const {PreciseDate} = require('@google-cloud/precise-date');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';
// const databaseId = 'my-database';
// const backupId = 'my-backup';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

// Gets a reference to a Cloud Spanner Database Admin Client object
const databaseAdminClient = spanner.getDatabaseAdminClient();

// Restore the database
console.log(
  `Restoring database ${databaseAdminClient.databasePath(
    projectId,
    instanceId,
    databaseId
  )} from backup ${backupId}.`
);
const [restoreOperation] = await databaseAdminClient.restoreDatabase({
  parent: databaseAdminClient.instancePath(projectId, instanceId),
  databaseId: databaseId,
  backup: databaseAdminClient.backupPath(projectId, instanceId, backupId),
});

// Wait for restore to complete
console.log('Waiting for database restore to complete...');
await restoreOperation.promise();

console.log('Database restored from backup.');
const [metadata] = await databaseAdminClient.getDatabase({
  name: databaseAdminClient.databasePath(projectId, instanceId, databaseId),
});
console.log(
  `Database ${metadata.restoreInfo.backupInfo.sourceDatabase} was restored ` +
    `to ${databaseId} from backup ${metadata.restoreInfo.backupInfo.backup} ` +
    'with version time ' +
    `${new PreciseDate(
      metadata.restoreInfo.backupInfo.versionTime
    ).toISOString()}.`
);

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;
use Google\Cloud\Spanner\Admin\Database\V1\RestoreDatabaseRequest;

/**
 * Restore a database from a backup.
 * Example:
 * ```
 * restore_backup($projectId, $instanceId, $databaseId, $backupId);
 * ```
 * @param string $projectId The Google Cloud project ID.
 * @param string $instanceId The Spanner instance ID.
 * @param string $databaseId The Spanner database ID.
 * @param string $backupId The Spanner backup ID.
 */
function restore_backup(
    string $projectId,
    string $instanceId,
    string $databaseId,
    string $backupId
): void {
    $databaseAdminClient = new DatabaseAdminClient();

    $backupName = DatabaseAdminClient::backupName($projectId, $instanceId, $backupId);
    $instanceName = DatabaseAdminClient::instanceName($projectId, $instanceId);

    $request = new RestoreDatabaseRequest([
        'parent' => $instanceName,
        'database_id' => $databaseId,
        'backup' => $backupName
    ]);

    $operationResponse = $databaseAdminClient->restoreDatabase($request);
    $operationResponse->pollUntilComplete();

    $database = $operationResponse->operationSucceeded() ? $operationResponse->getResult() : null;
    $restoreInfo = $database->getRestoreInfo();
    $backupInfo = $restoreInfo->getBackupInfo();
    $sourceDatabase = $backupInfo->getSourceDatabase();
    $sourceBackup = $backupInfo->getBackup();
    $versionTime = $backupInfo->getVersionTime()->getSeconds();
    printf(
        'Database %s restored from backup %s with version time %s' . PHP_EOL,
        $sourceDatabase, $sourceBackup, $versionTime
    );
}

Python

def restore_database(instance_id, new_database_id, backup_id):
    """Restores a database from a backup."""
    from google.cloud.spanner_admin_database_v1 import RestoreDatabaseRequest

    spanner_client = spanner.Client()
    database_admin_api = spanner_client.database_admin_api

    # Start restoring an existing backup to a new database.
    request = RestoreDatabaseRequest(
        parent=database_admin_api.instance_path(spanner_client.project, instance_id),
        database_id=new_database_id,
        backup=database_admin_api.backup_path(
            spanner_client.project, instance_id, backup_id
        ),
    )
    operation = database_admin_api.restore_database(request)

    # Wait for restore operation to complete.
    db = operation.result(1600)

    # Newly created database has restore information.
    restore_info = db.restore_info
    print(
        "Database {} restored to {} from backup {} with version time {}.".format(
            restore_info.backup_info.source_database,
            new_database_id,
            restore_info.backup_info.backup,
            restore_info.backup_info.version_time,
        )
    )

Ruby

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID of where to restore"
# backup_id = "Your Spanner backup ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/database"

database_admin_client = Google::Cloud::Spanner::Admin::Database.database_admin

instance_path = database_admin_client.instance_path project: project_id, instance: instance_id

db_path = database_admin_client.database_path project: project_id,
                                              instance: instance_id,
                                              database: database_id

backup_path = database_admin_client.backup_path project: project_id,
                                                instance: instance_id,
                                                backup: backup_id

job = database_admin_client.restore_database parent: instance_path,
                                             database_id: database_id,
                                             backup: backup_path

puts "Waiting for restore backup operation to complete"

job.wait_until_done!

database = database_admin_client.get_database name: db_path
restore_info = database.restore_info
puts "Database #{restore_info.backup_info.source_database} was restored to #{database_id} from backup #{restore_info.backup_info.backup} with version time #{restore_info.backup_info.version_time}"