Crea e gestisci le pianificazioni dei backup

Questa pagina descrive le operazioni di pianificazione dei backup di Spanner e spiega come impostare una pianificazione dei backup per il database.

Prima di iniziare

  • Per ottenere le autorizzazioni necessarie per creare e gestire le pianificazioni dei backup, chiedi all'amministratore di concederti seguenti ruoli IAM sull'istanza:

Crea una pianificazione del backup

Console

  1. Nella console Google Cloud, vai alla pagina Istanze di Spanner.

    Vai alla pagina Istanze Spanner

  2. Fai clic sull'istanza contenente il database.

  3. Fai clic sul database.

  4. Nel menu di navigazione, fai clic su Backup/Ripristino.

  5. Fai clic su Crea pianificazione backup.

  6. Compila il modulo, quindi fai clic su Crea.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi creare la pianificazione dei backup.
  • DATABASE_ID: l'ID del database in cui vuoi creare la pianificazione del backup.
  • RETENTION_DURATION: la durata di conservazione di i backup creati dalla pianificazione. Ad esempio, se vuoi che la durata del periodo di conservazione sia di un giorno, puoi utilizzare 86400s.
  • CRONTAB_EXPRESSION: l'espressione crontab per la frequenza della pianificazione del backup. Ad esempio, se vuoi che il la frequenza della pianificazione del backup ogni 12 ore, puoi usare 0 12 * * *.
  • BACKUP_TYPE: se si tratta di una pianificazione del backup completo o incrementale. I valori possibili sono full-backup o incremental-backup.
  • ENCRYPTION_TYPE: il tipo di crittografia dei backup creati dalla pianificazione dei backup. I valori possibili sono USE_DATABASE_ENCRYPTION, GOOGLE_DEFAULT_ENCRYPTION o CUSTOMER_MANAGED_ENCRYPTION. Se utilizzi CUSTOMER_MANAGED_ENCRYPTION, devi specificare un kmsKeyName. Se il tipo di backup è incremental-backup, il tipo di crittografia deve essere GOOGLE_DEFAULT_ENCRYPTION.

Esegui il seguente comando:

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules create SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID \
  --retention-duration=RETENTION_DURATION \
  --cron="CRONTAB_EXPRESSION" \
  --backup-type=BACKUP_TYPE \
  --encryption-type=ENCRYPTION_TYPE

Windows (PowerShell)

gcloud spanner backup-schedules create SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID `
  --retention-duration=RETENTION_DURATION `
  --cron="CRONTAB_EXPRESSION" `
  --backup-type=BACKUP_TYPE `
  --encryption-type=ENCRYPTION_TYPE

Windows (cmd.exe)

gcloud spanner backup-schedules create SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID ^
  --retention-duration=RETENTION_DURATION ^
  --cron="CRONTAB_EXPRESSION" ^
  --backup-type=BACKUP_TYPE ^
  --encryption-type=ENCRYPTION_TYPE

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi creare la pianificazione dei backup.
  • DATABASE_ID: L'ID del database in cui vuoi creare la pianificazione del backup.
  • SCHEDULE_ID: l'ID della pianificazione del backup.
  • BACKUP_TYPE: che si tratti di una pianificazione del backup completo o incrementale. I valori possibili sono fullBackupSpec o incrementalBackupSpec.
  • ENCRYPTION_TYPE: il tipo di crittografia dei backup creati dalla pianificazione dei backup. I valori possibili sono USE_DATABASE_ENCRYPTION, GOOGLE_DEFAULT_ENCRYPTION o CUSTOMER_MANAGED_ENCRYPTION. Se utilizzi CUSTOMER_MANAGED_ENCRYPTION, devi specificare un kmsKeyName. Se il tipo di backup è incremental-backup, il tipo di crittografia deve essere GOOGLE_DEFAULT_ENCRYPTION.
  • RETENTION_DURATION: la durata della conservazione dei backup creati dalla pianificazione.

Metodo HTTP e URL:

POST https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules?backup_schedule_id=SCHEDULE_ID

Corpo JSON della richiesta:

{
  "retentionDuration": "RETENTION_DURATION",
  "spec": {
    "cronSpec": {
      "text": "0 2 * * *"
    }
  },
  "encryptionConfig": {
    "encryptionType": "ENCRYPTION_TYPE"
  },
  "BACKUP_TYPE": {}
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID",
  "retentionDuration": "86400s",
  "encryptionConfig": {
    "encryptionType": "USE_DATABASE_ENCRYPTION"
  },
  "spec": {
    "cronSpec": {
      "text": "0 2 * * *",
      "timeZone": "UTC",
      "creationWindow": "14400s"
    }
  },
  "BACKUP_TYPE": {},
  "updateTime": "2024-05-22T11:13:51.835590Z"
}

Librerie client

C#

Per creare una pianificazione di backup completa, consulta il seguente codice di esempio:

using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class CreateFullBackupScheduleSample
{
    public BackupSchedule CreateFullBackupSchedule(string projectId, string instanceId, string databaseId, string scheduleId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        BackupSchedule response = client.CreateBackupSchedule(
            new CreateBackupScheduleRequest
            {
                ParentAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
                BackupScheduleId = scheduleId,
                BackupSchedule = new BackupSchedule
                {
                    Spec = new BackupScheduleSpec
                    {
                        CronSpec = new CrontabSpec
                        {
                            Text = "30 12 * * *",
                        }
                    },
                    RetentionDuration = new Duration
                    {
                        Seconds = 86400,
                    },
                    EncryptionConfig = new CreateBackupEncryptionConfig
                    {
                        EncryptionType = CreateBackupEncryptionConfig.Types.EncryptionType.UseDatabaseEncryption,
                    },
                    FullBackupSpec = new FullBackupSpec { },
                }
            });

        Console.WriteLine($"Created full backup schedule: {response}");
        return response;
    }
}
Per creare una pianificazione del backup incrementale, consulta il seguente codice di esempio:
using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class CreateIncrementalBackupScheduleSample
{
    public BackupSchedule CreateIncrementalBackupSchedule(string projectId, string instanceId, string databaseId, string scheduleId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        BackupSchedule response = client.CreateBackupSchedule(
            new CreateBackupScheduleRequest
            {
                ParentAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
                BackupScheduleId = scheduleId,
                BackupSchedule = new BackupSchedule
                {
                    Spec = new BackupScheduleSpec
                    {
                        CronSpec = new CrontabSpec
                        {
                            Text = "30 12 * * *",
                        }
                    },
                    RetentionDuration = new Duration
                    {
                        Seconds = 86400,
                    },
                    EncryptionConfig = new CreateBackupEncryptionConfig
                    {
                        EncryptionType = CreateBackupEncryptionConfig.Types.EncryptionType.GoogleDefaultEncryption,
                    },
                    IncrementalBackupSpec = new IncrementalBackupSpec { },
                }
            });

        Console.WriteLine($"Created incremental backup schedule: {response}");
        return response;
    }
}

C++

Per creare una pianificazione di backup completa, consulta il seguente codice di esempio:

void CreateFullBackupSchedule(
    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_schedule_id) {
  google::spanner::admin::database::v1::BackupSchedule backup_schedule;
  *backup_schedule.mutable_full_backup_spec() = {};
  backup_schedule.mutable_spec()->mutable_cron_spec()->set_text("30 12 * * *");
  backup_schedule.mutable_retention_duration()->set_seconds(3600 * 24);

  google::spanner::admin::database::v1::CreateBackupEncryptionConfig
      encryption_config;
  encryption_config.set_encryption_type(
      google::spanner::admin::database::v1::CreateBackupEncryptionConfig::
          USE_DATABASE_ENCRYPTION);
  *backup_schedule.mutable_encryption_config() = std::move(encryption_config);

  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  google::spanner::admin::database::v1::CreateBackupScheduleRequest request;
  request.set_parent(db.FullName());
  request.set_backup_schedule_id(backup_schedule_id);
  *request.mutable_backup_schedule() = std::move(backup_schedule);

  auto created_backup_schedule = client.CreateBackupSchedule(request);
  if (!created_backup_schedule) {
    throw std::move(created_backup_schedule).status();
  }
  std::cout << "Backup schedule " << created_backup_schedule->name()
            << " created at "
            << *google::cloud::spanner::MakeTimestamp(
                   created_backup_schedule->update_time());
}
Per creare una pianificazione del backup incrementale, consulta il seguente codice campione:
void CreateIncrementalBackupSchedule(
    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_schedule_id) {
  google::spanner::admin::database::v1::BackupSchedule backup_schedule;
  *backup_schedule.mutable_incremental_backup_spec() = {};
  backup_schedule.mutable_spec()->mutable_cron_spec()->set_text("30 12 * * *");
  backup_schedule.mutable_retention_duration()->set_seconds(3600 * 24);

  google::spanner::admin::database::v1::CreateBackupEncryptionConfig
      encryption_config;
  encryption_config.set_encryption_type(
      google::spanner::admin::database::v1::CreateBackupEncryptionConfig::
          GOOGLE_DEFAULT_ENCRYPTION);
  *backup_schedule.mutable_encryption_config() = std::move(encryption_config);

  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  google::spanner::admin::database::v1::CreateBackupScheduleRequest request;
  request.set_parent(db.FullName());
  request.set_backup_schedule_id(backup_schedule_id);
  *request.mutable_backup_schedule() = std::move(backup_schedule);

  auto created_backup_schedule = client.CreateBackupSchedule(request);
  if (!created_backup_schedule) {
    throw std::move(created_backup_schedule).status();
  }
  std::cout << "Incremental backup schedule " << created_backup_schedule->name()
            << " created at "
            << *google::cloud::spanner::MakeTimestamp(
                   created_backup_schedule->update_time());
}

Vai

Per creare una pianificazione di backup completa, consulta il seguente codice di esempio:


import (
	"context"
	"fmt"
	"io"
	"time"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
	"google.golang.org/protobuf/types/known/durationpb"
)

func createFullBackupSchedule(w io.Writer, dbName string, scheduleId string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// Create a schedule to create full backups daily at 12:30 AM, using the
	// database's encryption config, and retained for 24 hours.
	req := databasepb.CreateBackupScheduleRequest{
		Parent:           dbName,
		BackupScheduleId: scheduleId,
		BackupSchedule: &databasepb.BackupSchedule{
			Spec: &databasepb.BackupScheduleSpec{
				ScheduleSpec: &databasepb.BackupScheduleSpec_CronSpec{
					CronSpec: &databasepb.CrontabSpec{
						Text: "30 12 * * *",
					},
				},
			},
			RetentionDuration: durationpb.New(24 * time.Hour),
			EncryptionConfig: &databasepb.CreateBackupEncryptionConfig{
				EncryptionType: databasepb.CreateBackupEncryptionConfig_USE_DATABASE_ENCRYPTION,
			},
			BackupTypeSpec: &databasepb.BackupSchedule_FullBackupSpec{},
		},
	}

	res, err := client.CreateBackupSchedule(ctx, &req)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Created full backup schedule: %s", res)
	return nil
}
Per creare una pianificazione del backup incrementale, consulta il seguente codice di esempio:

import (
	"context"
	"fmt"
	"io"
	"time"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
	"google.golang.org/protobuf/types/known/durationpb"
)

func createIncrementalBackupSchedule(w io.Writer, dbName string, scheduleId string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// Create a schedule to create incremental backups daily at 12:30 AM, using
	// Google-managed encryption, and retained for 24 hours.
	req := databasepb.CreateBackupScheduleRequest{
		Parent:           dbName,
		BackupScheduleId: scheduleId,
		BackupSchedule: &databasepb.BackupSchedule{
			Spec: &databasepb.BackupScheduleSpec{
				ScheduleSpec: &databasepb.BackupScheduleSpec_CronSpec{
					CronSpec: &databasepb.CrontabSpec{
						Text: "30 12 * * *",
					},
				},
			},
			RetentionDuration: durationpb.New(24 * time.Hour),
			EncryptionConfig: &databasepb.CreateBackupEncryptionConfig{
				EncryptionType: databasepb.CreateBackupEncryptionConfig_GOOGLE_DEFAULT_ENCRYPTION,
			},
			BackupTypeSpec: &databasepb.BackupSchedule_IncrementalBackupSpec{},
		},
	}

	res, err := client.CreateBackupSchedule(ctx, &req)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Created incremental backup schedule: %s", res)
	return nil
}

Java

Per creare una pianificazione del backup completa, vedi il codice campione seguente:


import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.protobuf.Duration;
import com.google.spanner.admin.database.v1.BackupSchedule;
import com.google.spanner.admin.database.v1.BackupScheduleSpec;
import com.google.spanner.admin.database.v1.CreateBackupEncryptionConfig;
import com.google.spanner.admin.database.v1.CreateBackupScheduleRequest;
import com.google.spanner.admin.database.v1.CrontabSpec;
import com.google.spanner.admin.database.v1.DatabaseName;
import com.google.spanner.admin.database.v1.FullBackupSpec;
import java.io.IOException;

class CreateFullBackupScheduleSample {

  static void createFullBackupSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    String backupScheduleId = "my-backup-schedule";
    createFullBackupSchedule(projectId, instanceId, databaseId, backupScheduleId);
  }

  static void createFullBackupSchedule(
      String projectId, String instanceId, String databaseId, String backupScheduleId)
      throws IOException {
    final CreateBackupEncryptionConfig encryptionConfig =
        CreateBackupEncryptionConfig.newBuilder()
            .setEncryptionType(CreateBackupEncryptionConfig.EncryptionType.USE_DATABASE_ENCRYPTION)
            .build();
    final BackupSchedule backupSchedule =
        BackupSchedule.newBuilder()
            .setFullBackupSpec(FullBackupSpec.newBuilder().build())
            .setRetentionDuration(Duration.newBuilder().setSeconds(3600 * 24).build())
            .setSpec(
                BackupScheduleSpec.newBuilder()
                    .setCronSpec(CrontabSpec.newBuilder().setText("30 12 * * *").build())
                    .build())
            .setEncryptionConfig(encryptionConfig)
            .build();

    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      DatabaseName databaseName = DatabaseName.of(projectId, instanceId, databaseId);
      final BackupSchedule createdBackupSchedule =
          databaseAdminClient.createBackupSchedule(
              CreateBackupScheduleRequest.newBuilder()
                  .setParent(databaseName.toString())
                  .setBackupScheduleId(backupScheduleId)
                  .setBackupSchedule(backupSchedule)
                  .build());
      System.out.println(
          String.format(
              "Created backup schedule: %s\n%s",
              createdBackupSchedule.getName(), createdBackupSchedule.toString()));
    }
  }
}
Per creare una pianificazione del backup incrementale, consulta il seguente codice campione:

import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.protobuf.Duration;
import com.google.spanner.admin.database.v1.BackupSchedule;
import com.google.spanner.admin.database.v1.BackupScheduleSpec;
import com.google.spanner.admin.database.v1.CreateBackupEncryptionConfig;
import com.google.spanner.admin.database.v1.CreateBackupScheduleRequest;
import com.google.spanner.admin.database.v1.CrontabSpec;
import com.google.spanner.admin.database.v1.DatabaseName;
import com.google.spanner.admin.database.v1.IncrementalBackupSpec;
import java.io.IOException;

class CreateIncrementalBackupScheduleSample {

  static void createIncrementalBackupSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    String backupScheduleId = "my-backup-schedule";
    createIncrementalBackupSchedule(projectId, instanceId, databaseId, backupScheduleId);
  }

  static void createIncrementalBackupSchedule(
      String projectId, String instanceId, String databaseId, String backupScheduleId)
      throws IOException {
    final CreateBackupEncryptionConfig encryptionConfig =
        CreateBackupEncryptionConfig.newBuilder()
            .setEncryptionType(
                CreateBackupEncryptionConfig.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION)
            .build();
    final BackupSchedule backupSchedule =
        BackupSchedule.newBuilder()
            .setIncrementalBackupSpec(IncrementalBackupSpec.newBuilder().build())
            .setRetentionDuration(Duration.newBuilder().setSeconds(3600 * 24).build())
            .setSpec(
                BackupScheduleSpec.newBuilder()
                    .setCronSpec(CrontabSpec.newBuilder().setText("30 12 * * *").build())
                    .build())
            .setEncryptionConfig(encryptionConfig)
            .build();

    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      DatabaseName databaseName = DatabaseName.of(projectId, instanceId, databaseId);
      final BackupSchedule createdBackupSchedule =
          databaseAdminClient.createBackupSchedule(
              CreateBackupScheduleRequest.newBuilder()
                  .setParent(databaseName.toString())
                  .setBackupScheduleId(backupScheduleId)
                  .setBackupSchedule(backupSchedule)
                  .build());
      System.out.println(
          String.format(
              "Created incremental backup schedule: %s\n%s",
              createdBackupSchedule.getName(), createdBackupSchedule.toString()));
    }
  }
}

Node.js

Per creare una pianificazione di backup completa, consulta il seguente codice di esempio:

// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance-id';
// const databaseId = 'my-database-id';
// const scheduleId = 'my-schedule-id';

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // Create a schedule to create full backups daily at 12:30 AM, using the
  // database's encryption config, and retained for 24 hours.
  const [response] = await client.createBackupSchedule({
    parent: client.databasePath(projectId, instanceId, databaseId),
    backupScheduleId: scheduleId,
    backupSchedule: {
      spec: {
        cronSpec: {
          text: '30 12 * * *',
        },
      },
      retentionDuration: {
        seconds: 86400,
      },
      encryptionConfig: {
        encryptionType: 'USE_DATABASE_ENCRYPTION',
      },
      fullBackupSpec: {},
    },
  });
  console.log('Created full backup schedule:', response);
} catch (err) {
  console.error('ERROR:', err);
}
Per creare una pianificazione del backup incrementale, consulta il seguente codice di esempio:
// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance-id';
// const databaseId = 'my-database-id';
// const scheduleId = 'my-schedule-id';

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // Create a schedule to create incremental backups daily at 12:30 AM,
  // using Google-managed encryption, and retained for 24 hours.
  const [response] = await client.createBackupSchedule({
    parent: client.databasePath(projectId, instanceId, databaseId),
    backupScheduleId: scheduleId,
    backupSchedule: {
      spec: {
        cronSpec: {
          text: '30 12 * * *',
        },
      },
      retentionDuration: {
        seconds: 86400,
      },
      encryptionConfig: {
        encryptionType: 'GOOGLE_DEFAULT_ENCRYPTION',
      },
      incrementalBackupSpec: {},
    },
  });
  console.log('Created incremental backup schedule:', response);
} catch (err) {
  console.error('ERROR:', err);
}

Python

Per creare una pianificazione di backup completa, consulta il seguente codice di esempio:

def create_full_backup_schedule(
        instance_id: str,
        database_id: str,
        schedule_id: str,
) -> None:
    from datetime import timedelta
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb
    from google.cloud.spanner_admin_database_v1.types import \
        CreateBackupEncryptionConfig, FullBackupSpec

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.CreateBackupScheduleRequest(
        parent=database_admin_api.database_path(
            client.project,
            instance_id,
            database_id
        ),
        backup_schedule_id=schedule_id,
        backup_schedule=backup_schedule_pb.BackupSchedule(
            spec=backup_schedule_pb.BackupScheduleSpec(
                cron_spec=backup_schedule_pb.CrontabSpec(
                    text="30 12 * * *",
                ),
            ),
            retention_duration=timedelta(hours=24),
            encryption_config=CreateBackupEncryptionConfig(
                encryption_type=CreateBackupEncryptionConfig.EncryptionType.USE_DATABASE_ENCRYPTION,
            ),
            full_backup_spec=FullBackupSpec(),
        ),
    )

    response = database_admin_api.create_backup_schedule(request)
    print(f"Created full backup schedule: {response}")
Per creare una pianificazione del backup incrementale, consulta il seguente codice campione:
def create_incremental_backup_schedule(
        instance_id: str,
        database_id: str,
        schedule_id: str,
) -> None:
    from datetime import timedelta
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb
    from google.cloud.spanner_admin_database_v1.types import \
        CreateBackupEncryptionConfig, IncrementalBackupSpec

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.CreateBackupScheduleRequest(
        parent=database_admin_api.database_path(
            client.project,
            instance_id,
            database_id
        ),
        backup_schedule_id=schedule_id,
        backup_schedule=backup_schedule_pb.BackupSchedule(
            spec=backup_schedule_pb.BackupScheduleSpec(
                cron_spec=backup_schedule_pb.CrontabSpec(
                    text="30 12 * * *",
                ),
            ),
            retention_duration=timedelta(hours=24),
            encryption_config=CreateBackupEncryptionConfig(
                encryption_type=CreateBackupEncryptionConfig.EncryptionType.GOOGLE_DEFAULT_ENCRYPTION,
            ),
            incremental_backup_spec=IncrementalBackupSpec(),
        ),
    )

    response = database_admin_api.create_backup_schedule(request)
    print(f"Created incremental backup schedule: {response}")

Ottenere una pianificazione dei backup

Console

  1. Nella console Google Cloud, vai alla pagina Istanze di Spanner.

    Vai alla pagina Istanze Spanner

  2. Fai clic sull'istanza contenente il database.

  3. Fai clic sul database.

  4. Nel menu di navigazione, fai clic su Backup/Ripristino.

  5. Fai clic sulla scheda Pianificazioni per visualizzare tutte le pianificazioni dei backup e le relative informazioni.

gcloud

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.
  • SCHEDULE_ID: l'ID della pianificazione del backup.

Esegui il seguente comando:

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules describe SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID

Windows (PowerShell)

gcloud spanner backup-schedules describe SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID

Windows (cmd.exe)

gcloud spanner backup-schedules describe SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID

Dovresti ricevere una risposta simile alla seguente:

{
  encryptionConfig:
    encryptionType: USE_DATABASE_ENCRYPTION
  incrementalBackupSpec: {}
  name: projects/my-project/instances/my-instance/databases/my-database/backupSchedules/my-schedule
  retentionDuration: 2592000s
  spec:
    cronSpec:
      creationWindow: 14400s
      text: 0 */4 * * *
      timeZone: UTC
  updateTime: '2024-09-13T10:24:18.754839Z'
}

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.
  • SCHEDULE_ID: l'ID pianificazione dei backup.

Metodo HTTP e URL:

GET https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "name": "projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID",
  "retentionDuration": "100000s",
  "encryptionConfig": {
    "encryptionType": "USE_DATABASE_ENCRYPTION"
  },
  "spec": {
    "cronSpec": {
      "text": "0 2 * * *",
      "timeZone": "UTC",
      "creationWindow": "14400s"
    }
  },
  "fullBackupSpec": {},
  "updateTime": "2024-05-22T11:13:51.835590Z"
}

Librerie client

C#

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

public class GetBackupScheduleSample
{
    public BackupSchedule GetBackupSchedule(string projectId, string instanceId, string databaseId, string scheduleId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        BackupSchedule response = client.GetBackupSchedule(BackupScheduleName.FromProjectInstanceDatabaseSchedule(projectId, instanceId, databaseId, scheduleId));

        Console.WriteLine($"Backup schedule: {response}");
        return response;
    }
}

C++

void GetBackupSchedule(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_schedule_id) {
  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  std::string backup_schedule_name =
      db.FullName() + "/backupSchedules/" + backup_schedule_id;

  google::spanner::admin::database::v1::GetBackupScheduleRequest request;
  request.set_name(backup_schedule_name);

  auto backup_schedule = client.GetBackupSchedule(request);
  if (!backup_schedule) throw std::move(backup_schedule).status();
  std::cout << "Retrieved backup schedule:\n" << backup_schedule->DebugString();
}

Vai


import (
	"context"
	"fmt"
	"io"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
)

func getBackupSchedule(w io.Writer, dbName string, scheduleId string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	req := databasepb.GetBackupScheduleRequest{
		Name: fmt.Sprintf("%s/backupSchedules/%s", dbName, scheduleId),
	}

	res, err := client.GetBackupSchedule(ctx, &req)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Backup schedule: %s", res)
	return nil
}

Java


import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.spanner.admin.database.v1.BackupSchedule;
import com.google.spanner.admin.database.v1.BackupScheduleName;
import com.google.spanner.admin.database.v1.GetBackupScheduleRequest;
import java.io.IOException;

class GetBackupScheduleSample {

  static void getBackupSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    String backupScheduleId = "my-backup-schedule";
    getBackupSchedule(projectId, instanceId, databaseId, backupScheduleId);
  }

  static void getBackupSchedule(
      String projectId, String instanceId, String databaseId, String backupScheduleId)
      throws IOException {
    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      BackupScheduleName backupScheduleName =
          BackupScheduleName.of(projectId, instanceId, databaseId, backupScheduleId);
      final BackupSchedule backupSchedule =
          databaseAdminClient.getBackupSchedule(
              GetBackupScheduleRequest.newBuilder().setName(backupScheduleName.toString()).build());
      System.out.println(
          String.format(
              "Backup schedule: %s\n%s", backupSchedule.getName(), backupSchedule.toString()));
    }
  }
}

Node.js

// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance-id';
// const databaseId = 'my-database-id';
// const scheduleId = 'my-schedule-id';

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // Get the backup schedule.
  const [response] = await client.getBackupSchedule({
    name: client.backupSchedulePath(
      projectId,
      instanceId,
      databaseId,
      scheduleId
    ),
  });
  console.log('Backup schedule:', response);
} catch (err) {
  console.error('ERROR:', err);
}

Python

def get_backup_schedule(
        instance_id: str,
        database_id: str,
        schedule_id: str,
) -> None:
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.GetBackupScheduleRequest(
        name=database_admin_api.backup_schedule_path(
            client.project,
            instance_id,
            database_id,
            schedule_id,
        ),
    )

    response = database_admin_api.get_backup_schedule(request)
    print(f"Backup schedule: {response}")

Elenca pianificazioni backup

Console

  1. Nella console Google Cloud, vai alla pagina Istanze di Spanner.

    Vai alla pagina Istanze Spanner

  2. Fai clic sull'istanza contenente il database.

  3. Fai clic sul database.

  4. Nel menu di navigazione, fai clic su Backup/Ripristino.

  5. Fai clic sulla scheda Pianificazioni per visualizzare tutte le pianificazioni dei backup e le relative informazioni.

gcloud

Prima di utilizzare uno qualsiasi dei dati di comando riportati di seguito, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.

Esegui la persone che seguo :

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules list \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID

Windows (PowerShell)

gcloud spanner backup-schedules list `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID

Windows (cmd.exe)

gcloud spanner backup-schedules list ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID

Dovresti ricevere una risposta simile alla seguente:

Name Backup type Cron Retention duration Encryption type
my-full-schedule FULL 30 12 * * * 2592000s USE_DATABASE_ENCRYPTION
my-incr-schedule INCREMENTAL 0 */4 * * * 2592000s USE_DATABASE_ENCRYPTION

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID del database.

Metodo HTTP e URL:

GET https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "backupSchedules": [
    {
      "name": "projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID",
      "retentionDuration": "172800s",
      "encryptionConfig": {
        "encryptionType": "USE_DATABASE_ENCRYPTION"
      },
      "spec": {
        "cronSpec": {
          "text": "0 */12 * * *",
          "timeZone": "UTC",
          "creationWindow": "14400s"
        }
      },
      "fullBackupSpec": {},
      "updateTime": "2024-09-09T07:21:43.946180Z"
    },
    {
      "name": "projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID",
      "retentionDuration": "2592000s",
      "encryptionConfig": {
        "encryptionType": "CUSTOMER_MANAGED_ENCRYPTION",
        "kmsKeyName": "projects/PROJECT_ID/locations/us-central1/keyRings/cmek-demo/cryptoKeys/test-key"
      },
      "spec": {
        "cronSpec": {
          "text": "30 12 * * *",
          "timeZone": "UTC",
          "creationWindow": "14400s"
        }
      },
      "fullBackupSpec": {},
      "updateTime": "2024-09-17T18:27:53.868741Z"
    }
  ]
}

Librerie client

C#

using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Cloud.Spanner.Common.V1;
using System;
using System.Collections.Generic;

public class ListBackupSchedulesSample
{
    public IEnumerable<BackupSchedule> ListBackupSchedules(string projectId, string instanceId, string databaseId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        var backupSchedules = client.ListBackupSchedules(
            new ListBackupSchedulesRequest
            {
                ParentAsDatabaseName = DatabaseName.FromProjectInstanceDatabase(projectId, instanceId, databaseId),
            });

        foreach (BackupSchedule backupSchedule in backupSchedules)
        {
            Console.WriteLine($"Backup schedule: {backupSchedule}");
        }
        return backupSchedules;
    }
}

C++

void ListBackupSchedules(
    google::cloud::spanner_admin::DatabaseAdminClient client,
    std::string const& project_id, std::string const& instance_id,
    std::string const& database_id) {
  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  google::spanner::admin::database::v1::ListBackupSchedulesRequest request;
  request.set_parent(db.FullName());

  int count = 0;
  for (auto& backup_schedule : client.ListBackupSchedules(request)) {
    if (!backup_schedule) throw std::move(backup_schedule).status();

    std::cout << "Backup Schedule [" << ++count << "]:\n"
              << backup_schedule->DebugString();
  }
  if (count == 0) {
    std::cout << "No backup schedules found for database " << db.FullName();
  }
}

Vai


import (
	"context"
	"fmt"
	"io"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
	"google.golang.org/api/iterator"
)

func listBackupSchedules(w io.Writer, dbName string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	req := databasepb.ListBackupSchedulesRequest{
		Parent: dbName,
	}
	iter := client.ListBackupSchedules(ctx, &req)

	for {
		backupSchedule, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Fprintf(w, "Backup schedule: %s\n", backupSchedule)
	}

	return nil
}

Java


import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.spanner.admin.database.v1.BackupSchedule;
import com.google.spanner.admin.database.v1.DatabaseName;
import java.io.IOException;

class ListBackupSchedulesSample {

  static void listBackupSchedules() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    listBackupSchedules(projectId, instanceId, databaseId);
  }

  static void listBackupSchedules(String projectId, String instanceId, String databaseId)
      throws IOException {
    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      DatabaseName databaseName = DatabaseName.of(projectId, instanceId, databaseId);

      System.out.println(
          String.format("Backup schedules for database '%s'", databaseName.toString()));
      for (BackupSchedule backupSchedule :
          databaseAdminClient.listBackupSchedules(databaseName).iterateAll()) {
        System.out.println(
            String.format(
                "Backup schedule: %s\n%s", backupSchedule.getName(), backupSchedule.toString()));
      }
    }
  }
}

Node.js

// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

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

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // List backup schedules of a database.
  const [schedules] = await client.listBackupSchedules({
    parent: client.databasePath(projectId, instanceId, databaseId),
  });
  schedules.forEach(schedule => {
    console.log('Backup schedule:', schedule);
  });
} catch (err) {
  console.error('ERROR:', err);
}

Python

def list_backup_schedules(instance_id: str, database_id: str) -> None:
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.ListBackupSchedulesRequest(
        parent=database_admin_api.database_path(
            client.project,
            instance_id,
            database_id,
        ),
    )

    for backup_schedule in database_admin_api.list_backup_schedules(request):
        print(f"Backup schedule: {backup_schedule}")

Aggiornare una pianificazione del backup

Console

  1. Nella console Google Cloud, vai alla pagina Istanze di Spanner.

    Vai alla pagina Istanze Spanner

  2. Fai clic sull'istanza contenente il database.

  3. Fai clic sul database.

  4. Nel menu di navigazione, fai clic su Backup/Ripristino.

  5. Fai clic sulla scheda Pianificazioni.

  6. Seleziona Altre azioni per la pianificazione del backup e fai clic su Aggiorna.

  7. Puoi aggiornare la frequenza e il tempo di conservazione della pianificazione dei backup. Se si tratta di una pianificazione di backup completo, puoi anche aggiornare il tipo di crittografia.

  8. Fai clic su Salva.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi modificare la pianificazione dei backup.
  • DATABASE_ID: L'ID del database in cui vuoi modificare la pianificazione del backup.
  • RETENTION_DURATION: la durata di conservazione dei backup creati dalla pianificazione.
  • CRONTAB_EXPRESSION: l'espressione crontab per la frequenza della pianificazione del backup. Ad esempio, se vuoi che la frequenza della programmazione del backup sia ogni 12 ore, puoi utilizzare 0 12 * * *.
  • ENCRYPTION_TYPE: il tipo di crittografia dei backup creati dalla pianificazione dei backup. I valori possibili sono USE_DATABASE_ENCRYPTION e GOOGLE_DEFAULT_ENCRYPTION o CUSTOMER_MANAGED_ENCRYPTION. Se utilizzi CUSTOMER_MANAGED_ENCRYPTION, devi specificare un kmsKeyName. Se il tipo di backup è incremental-backup, il tipo di crittografia deve essere GOOGLE_DEFAULT_ENCRYPTION.

Esegui il seguente comando:

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules update SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID \
  --retention-duration=RETENTION_DURATION \
  --cron="CRONTAB_EXPRESSION" \
  --encryption-type=ENCRYPTION_TYPE

Windows (PowerShell)

gcloud spanner backup-schedules update SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID `
  --retention-duration=RETENTION_DURATION `
  --cron="CRONTAB_EXPRESSION" `
  --encryption-type=ENCRYPTION_TYPE

Windows (cmd.exe)

gcloud spanner backup-schedules update SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID ^
  --retention-duration=RETENTION_DURATION ^
  --cron="CRONTAB_EXPRESSION" ^
  --encryption-type=ENCRYPTION_TYPE

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi modificare la pianificazione dei backup.
  • DATABASE_ID: L'ID del database in cui vuoi modificare la pianificazione del backup.
  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • RETENTION_DURATION: la durata di conservazione di i backup creati dalla pianificazione. Ad esempio, se vuoi che la durata di conservazione sia di un giorno, specifica 86400s.
  • ENCRYPTION_TYPE: il tipo di crittografia dei backup creati dalla pianificazione dei backup. I valori possibili sono USE_DATABASE_ENCRYPTION e GOOGLE_DEFAULT_ENCRYPTION o CUSTOMER_MANAGED_ENCRYPTION. Se utilizzi CUSTOMER_MANAGED_ENCRYPTION, devi specificare un kmsKeyName. Se il tipo di backup è incremental-backup, il tipo di crittografia deve essere GOOGLE_DEFAULT_ENCRYPTION.

Metodo HTTP e URL:

PATCH https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID?updateMask=retention_duration,encryption_config,spec.cron_spec.text

Corpo JSON della richiesta:

{
  "retentionDuration": "RETENTION_DURATION",
  "spec": {
    "cronSpec": {
      "text": "0 2 * * *"
    }
    "encryptionConfig": {
      "encryptionType": "ENCRYPTION_TYPE"
    },
  },
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

  {
    "name": "projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID",
    "retentionDuration": "86400s",
    "encryptionConfig": {
      "encryptionType": "USE_DATABASE_ENCRYPTION"
    },
    "spec": {
      "cronSpec": {
        "text": "0 2 * * *",
        "timeZone": "UTC",
        "creationWindow": "14400s"
      }
    },
    "fullBackupSpec": {},
    "updateTime": "2024-05-22T11:13:51.835590Z"
  }

Librerie client

C#

using Google.Cloud.Spanner.Admin.Database.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class UpdateBackupScheduleSample
{
    public BackupSchedule UpdateBackupSchedule(string projectId, string instanceId, string databaseId, string scheduleId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        BackupSchedule response = client.UpdateBackupSchedule(
            new UpdateBackupScheduleRequest
            {
                BackupSchedule = new BackupSchedule
                {
                    BackupScheduleName = BackupScheduleName.FromProjectInstanceDatabaseSchedule(projectId, instanceId, databaseId, scheduleId),
                    Spec = new BackupScheduleSpec
                    {
                        CronSpec = new CrontabSpec
                        {
                            Text = "45 15 * * *",
                        },
                    },
                    RetentionDuration = new Duration
                    {
                        Seconds = 172800,
                    },
                    EncryptionConfig = new CreateBackupEncryptionConfig
                    {
                        EncryptionType = CreateBackupEncryptionConfig.Types.EncryptionType.UseDatabaseEncryption,
                    },
                },
                UpdateMask = new FieldMask
                {
                    Paths = { "spec.cron_spec.text", "retention_duration", "encryption_config" },
                },
            });

        Console.WriteLine($"Updated backup schedule: {response}");
        return response;
    }
}

C++

void UpdateBackupSchedule(
    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_schedule_id) {
  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  std::string backup_schedule_name =
      db.FullName() + "/backupSchedules/" + backup_schedule_id;

  google::spanner::admin::database::v1::BackupSchedule backup_schedule;
  backup_schedule.set_name(backup_schedule_name);
  backup_schedule.mutable_spec()->mutable_cron_spec()->set_text("45 15 * * *");
  backup_schedule.mutable_retention_duration()->set_seconds(3600 * 48);

  google::spanner::admin::database::v1::CreateBackupEncryptionConfig
      encryption_config;
  encryption_config.set_encryption_type(
      google::spanner::admin::database::v1::CreateBackupEncryptionConfig::
          USE_DATABASE_ENCRYPTION);
  *backup_schedule.mutable_encryption_config() = std::move(encryption_config);

  google::protobuf::FieldMask update_mask;
  update_mask.add_paths("spec.cron_spec.text");
  update_mask.add_paths("retention_duration");
  update_mask.add_paths("encryption_config");

  google::spanner::admin::database::v1::UpdateBackupScheduleRequest request;
  *request.mutable_backup_schedule() = std::move(backup_schedule);
  *request.mutable_update_mask() = std::move(update_mask);

  auto updated_backup_schedule = client.UpdateBackupSchedule(request);
  if (!updated_backup_schedule) {
    throw std::move(updated_backup_schedule).status();
  }
  std::cout << "Backup schedule " << updated_backup_schedule->name()
            << " updated at "
            << *google::cloud::spanner::MakeTimestamp(
                   updated_backup_schedule->update_time());
}

Vai


import (
	"context"
	"fmt"
	"io"
	"time"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

func updateBackupSchedule(w io.Writer, dbName string, scheduleId string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// Update a schedule to create backups daily at 3:45 PM, using the database's
	// encryption config, and retained for 48 hours.
	req := databasepb.UpdateBackupScheduleRequest{
		BackupSchedule: &databasepb.BackupSchedule{
			Name: fmt.Sprintf("%s/backupSchedules/%s", dbName, scheduleId),
			Spec: &databasepb.BackupScheduleSpec{
				ScheduleSpec: &databasepb.BackupScheduleSpec_CronSpec{
					CronSpec: &databasepb.CrontabSpec{
						Text: "45 15 * * *",
					},
				},
			},
			RetentionDuration: durationpb.New(48 * time.Hour),
			EncryptionConfig: &databasepb.CreateBackupEncryptionConfig{
				EncryptionType: databasepb.CreateBackupEncryptionConfig_USE_DATABASE_ENCRYPTION,
			},
		},
		UpdateMask: &fieldmaskpb.FieldMask{
			Paths: []string{
				"spec.cron_spec.text",
				"retention_duration",
				"encryption_config",
			},
		},
	}

	res, err := client.UpdateBackupSchedule(ctx, &req)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Updated backup schedule: %s", res)
	return nil
}

Java


import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.spanner.admin.database.v1.BackupSchedule;
import com.google.spanner.admin.database.v1.BackupScheduleName;
import com.google.spanner.admin.database.v1.BackupScheduleSpec;
import com.google.spanner.admin.database.v1.CreateBackupEncryptionConfig;
import com.google.spanner.admin.database.v1.CrontabSpec;
import com.google.spanner.admin.database.v1.UpdateBackupScheduleRequest;
import java.io.IOException;

class UpdateBackupScheduleSample {

  static void updateBackupSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    String backupScheduleId = "my-backup-schedule";
    updateBackupSchedule(projectId, instanceId, databaseId, backupScheduleId);
  }

  static void updateBackupSchedule(
      String projectId, String instanceId, String databaseId, String backupScheduleId)
      throws IOException {
    BackupScheduleName backupScheduleName =
        BackupScheduleName.of(projectId, instanceId, databaseId, backupScheduleId);
    final CreateBackupEncryptionConfig encryptionConfig =
        CreateBackupEncryptionConfig.newBuilder()
            .setEncryptionType(CreateBackupEncryptionConfig.EncryptionType.USE_DATABASE_ENCRYPTION)
            .build();
    final BackupSchedule backupSchedule =
        BackupSchedule.newBuilder()
            .setName(backupScheduleName.toString())
            .setRetentionDuration(Duration.newBuilder().setSeconds(3600 * 48))
            .setSpec(
                BackupScheduleSpec.newBuilder()
                    .setCronSpec(CrontabSpec.newBuilder().setText("45 15 * * *").build())
                    .build())
            .setEncryptionConfig(encryptionConfig)
            .build();

    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      final FieldMask fieldMask =
          FieldMask.newBuilder()
              .addPaths("retention_duration")
              .addPaths("spec.cron_spec.text")
              .addPaths("encryption_config")
              .build();
      final BackupSchedule updatedBackupSchedule =
          databaseAdminClient.updateBackupSchedule(
              UpdateBackupScheduleRequest.newBuilder()
                  .setBackupSchedule(backupSchedule)
                  .setUpdateMask(fieldMask)
                  .build());
      System.out.println(
          String.format(
              "Updated backup schedule: %s\n%s",
              updatedBackupSchedule.getName(), updatedBackupSchedule.toString()));
    }
  }
}

Node.js

// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance-id';
// const databaseId = 'my-database-id';
// const scheduleId = 'my-schedule-id';

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // Update the schedule to create backups daily at 3:45 PM, using the
  // database's encryption config, and retained for 48 hours.
  const [response] = await client.updateBackupSchedule({
    backupSchedule: {
      name: client.backupSchedulePath(
        projectId,
        instanceId,
        databaseId,
        scheduleId
      ),
      spec: {
        cronSpec: {
          text: '45 15 * * *',
        },
      },
      retentionDuration: {
        seconds: 172800,
      },
      encryptionConfig: {
        encryptionType: 'USE_DATABASE_ENCRYPTION',
      },
    },
    updateMask: {
      paths: [
        'spec.cron_spec.text',
        'retention_duration',
        'encryption_config',
      ],
    },
  });
  console.log('Updated backup schedule:', response);
} catch (err) {
  console.error('ERROR:', err);
}

Python

def update_backup_schedule(
        instance_id: str,
        database_id: str,
        schedule_id: str,
) -> None:
    from datetime import timedelta
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb
    from google.cloud.spanner_admin_database_v1.types import \
        CreateBackupEncryptionConfig
    from google.protobuf.field_mask_pb2 import FieldMask

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.UpdateBackupScheduleRequest(
        backup_schedule=backup_schedule_pb.BackupSchedule(
            name=database_admin_api.backup_schedule_path(
                client.project,
                instance_id,
                database_id,
                schedule_id,
            ),
            spec=backup_schedule_pb.BackupScheduleSpec(
                cron_spec=backup_schedule_pb.CrontabSpec(
                    text="45 15 * * *",
                ),
            ),
            retention_duration=timedelta(hours=48),
            encryption_config=CreateBackupEncryptionConfig(
                encryption_type=CreateBackupEncryptionConfig.EncryptionType.USE_DATABASE_ENCRYPTION,
            ),
        ),
        update_mask=FieldMask(
            paths=[
                "spec.cron_spec.text",
                "retention_duration",
                "encryption_config",
            ],
        ),
    )

    response = database_admin_api.update_backup_schedule(request)
    print(f"Updated backup schedule: {response}")

Eliminare una pianificazione del backup

Console

  1. Nella console Google Cloud, vai alla pagina Istanze di Spanner.

    Vai alla pagina Istanze Spanner

  2. Fai clic sull'istanza contenente il database.

  3. Fai clic sul database.

  4. Nel menu di navigazione, fai clic su Backup/Ripristino.

  5. Seleziona Altre azioni per la pianificazione del backup e fai clic su Elimina.

  6. Digita il nome della pianificazione del backup.

  7. Fai clic su Conferma.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi eliminare la pianificazione del backup.
  • DATABASE_ID: l'ID del database in cui vuoi eliminare la pianificazione del backup.

Esegui la persone che seguo :

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules delete SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID

Windows (PowerShell)

gcloud spanner backup-schedules delete SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID

Windows (cmd.exe)

gcloud spanner backup-schedules delete SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID dell'istanza in cui vuoi eliminare la pianificazione del backup.
  • DATABASE_ID: L'ID del database in cui vuoi eliminare la pianificazione del backup.
  • SCHEDULE_ID: l'ID pianificazione dei backup.

Metodo HTTP e URL:

DELETE https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere un codice di stato di operazione riuscita (2xx) e una risposta vuota.

Librerie client

C#

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

public class DeleteBackupScheduleSample
{
    public void DeleteBackupSchedule(string projectId, string instanceId, string databaseId, string scheduleId)
    {
        DatabaseAdminClient client = DatabaseAdminClient.Create();

        client.DeleteBackupSchedule(BackupScheduleName.FromProjectInstanceDatabaseSchedule(projectId, instanceId, databaseId, scheduleId));

        Console.WriteLine("Deleted backup schedule");
    }
}

C++

void DeleteBackupSchedule(
    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_schedule_id) {
  google::cloud::spanner::Database db(project_id, instance_id, database_id);
  std::string backup_schedule_name =
      db.FullName() + "/backupSchedules/" + backup_schedule_id;

  google::spanner::admin::database::v1::DeleteBackupScheduleRequest request;
  request.set_name(backup_schedule_name);

  auto status = client.DeleteBackupSchedule(request);
  if (!status.ok()) throw std::move(status);
  std::cout << "Backup schedule " << backup_schedule_name << " deleted";
}

Vai


import (
	"context"
	"fmt"
	"io"

	database "cloud.google.com/go/spanner/admin/database/apiv1"
	"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
)

func deleteBackupSchedule(w io.Writer, dbName string, scheduleId string) error {
	ctx := context.Background()

	client, err := database.NewDatabaseAdminClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	req := databasepb.DeleteBackupScheduleRequest{
		Name: fmt.Sprintf("%s/backupSchedules/%s", dbName, scheduleId),
	}

	err = client.DeleteBackupSchedule(ctx, &req)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Deleted backup schedule")
	return nil
}

Java


import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient;
import com.google.spanner.admin.database.v1.BackupScheduleName;
import com.google.spanner.admin.database.v1.DeleteBackupScheduleRequest;
import java.io.IOException;

class DeleteBackupScheduleSample {

  static void deleteBackupSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    String databaseId = "my-database";
    String backupScheduleId = "my-backup-schedule";
    deleteBackupSchedule(projectId, instanceId, databaseId, backupScheduleId);
  }

  static void deleteBackupSchedule(
      String projectId, String instanceId, String databaseId, String backupScheduleId)
      throws IOException {
    try (DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.create()) {
      BackupScheduleName backupScheduleName =
          BackupScheduleName.of(projectId, instanceId, databaseId, backupScheduleId);
      databaseAdminClient.deleteBackupSchedule(
          DeleteBackupScheduleRequest.newBuilder().setName(backupScheduleName.toString()).build());
      System.out.println(
          String.format("Deleted backup schedule: %s", backupScheduleName.toString()));
    }
  }
}

Node.js

// Import the Google Cloud client library for Spanner.
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance-id';
// const databaseId = 'my-database-id';
// const scheduleId = 'my-schedule-id';

// Create a Spanner database admin client.
const spanner = new Spanner({projectId});
const client = spanner.getDatabaseAdminClient();

try {
  // Delete the backup schedule.
  await client.deleteBackupSchedule({
    name: client.backupSchedulePath(
      projectId,
      instanceId,
      databaseId,
      scheduleId
    ),
  });
  console.log('Deleted backup schedule');
} catch (err) {
  console.error('ERROR:', err);
}

Python

def delete_backup_schedule(
        instance_id: str,
        database_id: str,
        schedule_id: str,
) -> None:
    from google.cloud import spanner
    from google.cloud.spanner_admin_database_v1.types import \
        backup_schedule as backup_schedule_pb

    client = spanner.Client()
    database_admin_api = client.database_admin_api

    request = backup_schedule_pb.DeleteBackupScheduleRequest(
        name=database_admin_api.backup_schedule_path(
            client.project,
            instance_id,
            database_id,
            schedule_id,
        ),
    )

    database_admin_api.delete_backup_schedule(request)
    print("Deleted backup schedule")

Imposta criterio di controllo dell'accesso IAM

Puoi impostare un criterio di accesso IAM per specificare chi ha accesso alla programmazione del backup.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.

Esegui la persone che seguo :

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules set-iam-policy SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID \
  policy.json

Windows (PowerShell)

gcloud spanner backup-schedules set-iam-policy SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID `
  policy.json

Windows (cmd.exe)

gcloud spanner backup-schedules set-iam-policy SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID ^
  policy.json

Dovresti ricevere una risposta simile alla seguente:

Updated IAM policy for backupSchedule [SCHEDULE_ID].
bindings:
- members:
  - user:test@google.com
  role: roles/editor
etag: BwYi82k-fho=
version: 1
Di seguito è riportato un esempio di file policy.json che puoi utilizzare insieme a questo Comando gcloud CLI:
{
"version": 1,
"etag": "BwYi8ypICC0=",
"bindings": [
  {
    "role": "roles/editor",
    "members": [
      "user:test@gmail.com"
    ]
  }
]
}

REST v1

Prima di utilizzare i dati della richiesta, effettua le seguenti sostituzioni:

  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.
  • SCHEDULE_ID: l'ID pianificazione dei backup.

Metodo HTTP e URL:

POST https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID:setIamPolicy?alt=json

Corpo JSON della richiesta:

{
  "policy": {
    "version": 1,
    "etag": "BwYi8ypICC0=",
    "bindings": [
      {
        "role": "roles/editor",
        "members": [
          "user:test@gmail.com"
        ]
      }
    ]
  }
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  {
    "version": 1,
    "etag": "etag",
    "bindings": [
      {
        "role": "roles/non-primitive",
        "members": [
          "user:test@gmail.com"
        ]
      }
    ]
  }
}

Ottieni criterio di controllo dell'accesso IAM

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.
  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.

Esegui la persone che seguo :

Linux, macOS o Cloud Shell

gcloud spanner backup-schedules get-iam-policy SCHEDULE_ID \
  --project=PROJECT_ID \
  --instance=INSTANCE_ID \
  --database=DATABASE_ID

Windows (PowerShell)

gcloud spanner backup-schedules get-iam-policy SCHEDULE_ID `
  --project=PROJECT_ID `
  --instance=INSTANCE_ID `
  --database=DATABASE_ID

Windows (cmd.exe)

gcloud spanner backup-schedules get-iam-policy SCHEDULE_ID ^
  --project=PROJECT_ID ^
  --instance=INSTANCE_ID ^
  --database=DATABASE_ID

Dovresti ricevere una risposta simile alla seguente:

bindings:
- members:
  - user:test@gmail.com
  role: roles/editor
etag: BwYi82k-fho=
version: 1

REST v1

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • INSTANCE_ID: l'ID istanza.
  • DATABASE_ID: l'ID database.
  • SCHEDULE_ID: l'ID pianificazione dei backup.
  • PROJECT_ID: l'ID progetto.

Metodo HTTP e URL:

POST https://spanner.googleapis.com/v1/projects/PROJECT_ID/instances/INSTANCE_ID/databases/DATABASE_ID/backupSchedules/SCHEDULE_ID:getIamPolicy?alt=json

Per inviare la richiesta, espandi una delle seguenti opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  {
    "version": 1,
    "etag": "BwYbyZ9pc4o=",
    "bindings": [
      {
        "role": "roles/editor",
        "members": [
          "user:test@gmail.com"
        ]
      }
    ]
  }
}

Passaggi successivi