Gestione della replica turbo

Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.

Vai ai concetti

In questa pagina viene descritto come utilizzare la funzionalità di replica turbo in un bucket a doppia area geografica.

Autorizzazioni obbligatorie

Console

Per completare questa guida utilizzando la console Google Cloud, devi disporre delle autorizzazioni IAM appropriate. Per utilizzare questa funzionalità, devi avere o intendi creare un bucket in una località a doppia area geografica. Se il bucket a cui vuoi accedere esiste in un progetto che non hai creato, potresti aver bisogno che il proprietario del progetto ti assegni un ruolo contenente le autorizzazioni necessarie.

Per un elenco delle autorizzazioni necessarie per azioni specifiche, consulta Autorizzazioni IAM per la console Google Cloud.

Per un elenco dei ruoli pertinenti, consulta Ruoli Cloud Storage. In alternativa, puoi creare un ruolo personalizzato con autorizzazioni specifiche e limitate.

Riga di comando

Per completare questa guida utilizzando un'utilità a riga di comando, devi disporre delle autorizzazioni IAM appropriate. Per utilizzare questa funzionalità, devi avere o intendi creare un bucket in una località a doppia area geografica. Se il bucket a cui vuoi accedere esiste in un progetto che non hai creato, potresti aver bisogno che il proprietario del progetto ti assegni un ruolo contenente le autorizzazioni necessarie.

Per un elenco delle autorizzazioni necessarie per azioni specifiche, consulta Autorizzazioni IAM per i comandi gsutil.

Per un elenco dei ruoli pertinenti, consulta Ruoli Cloud Storage. In alternativa, puoi creare un ruolo personalizzato con autorizzazioni specifiche e limitate.

Librerie client

Per completare questa guida utilizzando le librerie client di Cloud Storage, devi disporre delle autorizzazioni IAM appropriate. Per utilizzare questa funzionalità, devi avere o intendi creare un bucket in una località con doppia regione. Se il bucket a cui vuoi accedere esiste in un progetto che non hai creato, potresti aver bisogno che il proprietario del progetto ti assegni un ruolo contenente le autorizzazioni necessarie.

Se non diversamente specificato, le richieste della libreria client vengono effettuate tramite l'API JSON e richiedono le autorizzazioni elencate nelle autorizzazioni IAM per i metodi JSON. Per vedere quali metodi dell'API JSON vengono richiamati quando effettui richieste utilizzando una libreria client, registra le richieste non elaborate.

Per un elenco di ruoli IAM pertinenti, consulta i ruoli Cloud Storage. In alternativa, puoi creare un ruolo personalizzato con autorizzazioni specifiche e limitate.

API REST

API JSON

Per completare questa guida utilizzando l'API JSON, devi disporre delle autorizzazioni IAM appropriate. Per utilizzare questa funzionalità, devi avere o intendi creare un bucket in una località a doppia area geografica. Se il bucket a cui vuoi accedere esiste in un progetto che non hai creato, potresti aver bisogno che il proprietario del progetto ti assegni un ruolo contenente le autorizzazioni necessarie.

Per un elenco delle autorizzazioni necessarie per azioni specifiche, consulta la pagina relativa alle autorizzazioni IAM per i metodi JSON.

Per un elenco dei ruoli pertinenti, consulta Ruoli Cloud Storage. In alternativa, puoi creare un ruolo personalizzato con autorizzazioni specifiche e limitate.

API XML

Questa funzionalità non può essere gestita tramite l'API XML. Usa l'API JSON.

Imposta replica turbo

Per abilitare o disabilitare la replica turbo in un bucket esistente, segui queste istruzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket desiderato.

  3. Fai clic sulla scheda Configuration (Configurazione).

  4. Nella riga Replica, fai clic su Modifica.

    La finestra visualizzata indica se stai per abilitare la replica turbo o disattivare la replica turbo.

  5. Fai clic su Salva per confermare la nuova impostazione.

Riga di comando

gcloud

Utilizza il comando gcloud storage buckets update con il flag --rpo:

gcloud storage buckets update gs://BUCKET_NAME --rpo=STATE

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

  • STATE è ASYNC_TURBO per abilitare la replica turbo o DEFAULT per disabilitare la replica turbo.

Se l'operazione ha esito positivo, la risposta avrà il seguente aspetto:

Updating gs://my-bucket/...
  Completed 1  

gsutil

Utilizza il comando gsutil rpo set:

gsutil rpo set STATE gs://BUCKET_NAME/

Dove:

  • STATE è ASYNC_TURBO per abilitare la replica turbo o DEFAULT per disabilitare la replica turbo.

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

Se l'operazione ha esito positivo, non viene restituita una risposta. La modifica entra in vigore immediatamente.

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage C++.

Il seguente esempio abilita la replica turbo su un bucket:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto updated = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRpo(gcs::RpoAsyncTurbo()));
  if (!updated) throw std::move(updated).status();

  std::cout << "RPO is set to 'ASYNC_TURBO' for " << updated->name() << "\n";
}

L'esempio seguente abilita la replica predefinita su un bucket:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto updated = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetRpo(gcs::RpoDefault()));
  if (!updated) throw std::move(updated).status();

  std::cout << "RPO is set to 'default' for " << updated->name() << "\n";
}

C#

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage C#.

Il seguente esempio abilita la replica turbo su un bucket:

// Copyright 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Google.Cloud.Storage.V1;

public class SetRpoAsyncTurboSample
{
    public void SetRpoAsyncTurbo(string bucketName = "your-unique-bucket-name")
    {
        // Enabling turbo replication requires a bucket with dual-region configuration
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Rpo = "ASYNC_TURBO";
        storage.UpdateBucket(bucket);

        Console.WriteLine($"Turbo replication enabled for bucket {bucketName}");
    }
}

L'esempio seguente abilita la replica predefinita su un bucket:

// Copyright 2021 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using Google.Cloud.Storage.V1;

public class SetRpoDefaultSample
{
    public void SetRpoDefault(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Rpo = "DEFAULT";
        storage.UpdateBucket(bucket);

        Console.WriteLine($"Turbo replication disabled for bucket {bucketName}");
    }
}

Go

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Go.

Il seguente esempio abilita la replica turbo su un bucket:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package buckets

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

	"cloud.google.com/go/storage"
)

// setRPOAsyncTurbo enables turbo replication for the bucket by setting RPO to
// "ASYNC_TURBO". The bucket must be dual-region to use this feature.
func setRPOAsyncTurbo(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setRPO := storage.BucketAttrsToUpdate{
		RPO: storage.RPOAsyncTurbo,
	}
	if _, err := bucket.Update(ctx, setRPO); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication enabled for %v", bucketName)
	return nil
}

L'esempio seguente abilita la replica predefinita su un bucket:

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package buckets

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

	"cloud.google.com/go/storage"
)

// setRPODefault disables turbo replication for the bucket by setting RPO to
// "DEFAULT".
func setRPODefault(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	setRPO := storage.BucketAttrsToUpdate{
		RPO: storage.RPODefault,
	}
	if _, err := bucket.Update(ctx, setRPO); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication disabled for %v", bucketName)
	return nil
}

Java

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Java.

Il seguente esempio abilita la replica turbo su un bucket:

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.storage.bucket;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Rpo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetAsyncTurboRpo {
  public static void setAsyncTurboRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    bucket.toBuilder().setRpo(Rpo.ASYNC_TURBO).build().update();

    System.out.println("Turbo replication was enabled for " + bucketName);
  }
}

L'esempio seguente abilita la replica predefinita su un bucket:

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.storage.bucket;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Rpo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetDefaultRpo {
  public static void setDefaultRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);

    bucket.toBuilder().setRpo(Rpo.DEFAULT).build().update();

    System.out.println("Replication was set to default for " + bucketName);
  }
}

Node.js

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Node.js.

Il seguente esempio abilita la replica turbo su un bucket:

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This application demonstrates how to perform basic operations on buckets with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket') {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The name of your GCS bucket in a dual-region
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  // Enable turbo replication for the bucket by setting rpo to ASYNC_TURBO.
  // The bucket must be a dual-region bucket.
  async function setRPOAsyncTurbo() {
    await storage.bucket(bucketName).setMetadata({
      rpo: 'ASYNC_TURBO',
    });

    console.log(`Turbo replication enabled for ${bucketName}.`);
  }

  setRPOAsyncTurbo();
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));

L'esempio seguente abilita la replica predefinita su un bucket:

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * This application demonstrates how to perform basic operations on buckets with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket') {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // The name of your GCS bucket in a dual-region
  // const bucketName = 'Name of a bucket, e.g. my-bucket';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  // Disable turbo replication for the bucket by setting RPO to default.
  // The bucket must be a dual-region bucket.
  async function setRPODefault() {
    await storage.bucket(bucketName).setMetadata({
      rpo: 'DEFAULT',
    });

    console.log(`Turbo replication disabled for ${bucketName}.`);
  }

  setRPODefault();
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));

PHP

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage PHP.

Il seguente esempio abilita la replica turbo su un bucket:

<?php
/**
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/main/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket's Turbo Replication(rpo) setting to `ASYNC_TURBO`.
 * The bucket must be a dual-region bucket.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_rpo_async_turbo(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $rpo = 'ASYNC_TURBO';

    $bucket->update([
        'rpo' => $rpo
    ]);

    printf(
        'The replication behavior or recovery point objective (RPO) has been set to ASYNC_TURBO for %s.' . PHP_EOL,
        $bucketName
    );
}

// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

L'esempio seguente abilita la replica predefinita su un bucket:

<?php
/**
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/main/storage/README.md
 */

namespace Google\Cloud\Samples\Storage;

use Google\Cloud\Storage\StorageClient;

/**
 * Set the bucket's replication behavior or recovery point objective (RPO) to `DEFAULT`.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function set_rpo_default(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $rpo = 'DEFAULT';

    // Updating the rpo value of a multi-region bucket to DEFAULT has no effect
    // and updating the rpo value of a regional bucket will throw an exception.
    $bucket->update([
        'rpo' => $rpo
    ]);

    printf(
        'The replication behavior or recovery point objective (RPO) has been set to DEFAULT for %s.' . PHP_EOL,
        $bucketName
    );
}

// The following 2 lines are only needed to run the samples
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

Python

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Python.

Il seguente esempio abilita la replica turbo su un bucket:

#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

"""Sample that sets RPO (Recovery Point Objective) to ASYNC_TURBO
This sample is used on this page:
    https://cloud.google.com/storage/docs/managing-turbo-replication
For more information, see README.md.
"""

from google.cloud import storage
from google.cloud.storage.constants import RPO_ASYNC_TURBO

def set_rpo_async_turbo(bucket_name):
    """Sets the RPO to ASYNC_TURBO, enabling the turbo replication feature"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_ASYNC_TURBO
    bucket.patch()

    print(f"RPO is set to ASYNC_TURBO for {bucket.name}.")

if __name__ == "__main__":
    set_rpo_async_turbo(bucket_name=sys.argv[1])

L'esempio seguente abilita la replica predefinita su un bucket:

#!/usr/bin/env python

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

"""Sample that sets the replication behavior or recovery point objective (RPO) to default.
This sample is used on this page:
    https://cloud.google.com/storage/docs/managing-turbo-replication
For more information, see README.md.
"""

from google.cloud import storage
from google.cloud.storage.constants import RPO_DEFAULT

def set_rpo_default(bucket_name):
    """Sets the RPO to DEFAULT, disabling the turbo replication feature"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_DEFAULT
    bucket.patch()

    print(f"RPO is set to DEFAULT for {bucket.name}.")

if __name__ == "__main__":
    set_rpo_default(bucket_name=sys.argv[1])

Ruby

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Ruby.

Il seguente esempio abilita la replica turbo su un bucket:

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def set_rpo_async_turbo bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name,
                           location: "ASIA"

  bucket.rpo = :ASYNC_TURBO

  puts "Turbo replication is enabled for #{bucket_name}."
end

set_rpo_async_turbo bucket_name: ARGV.shift if $PROGRAM_NAME == __FILE__

L'esempio seguente abilita la replica predefinita su un bucket:

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

def set_rpo_default bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.rpo = :DEFAULT

  puts "The replication behavior or recovery point objective (RPO) for #{bucket_name} is set to default."
end

set_rpo_default bucket_name: ARGV.shift if $PROGRAM_NAME == __FILE__

API REST

API JSON

  1. Richiedi un token di accesso all'autorizzazione da Playground OAuth 2.0. Configura il parco giochi in modo che utilizzi le tue credenziali OAuth. Per le istruzioni, consulta Autenticazione API.
  2. Crea un file JSON contenente le seguenti informazioni:

    {
      "rpo": "STATE"
    }

    Dove STATE è ASYNC_TURBO per abilitare la replica turbo o DEFAULT per disabilitare la replica turbo.

  3. Usa cURL per chiamare l'API JSON con una PATCH Bucket:

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=rpo"

    Dove:

    • JSON_FILE_NAME è il percorso del file JSON che hai creato nel passaggio 2.
    • OAUTH2_TOKEN è il token di accesso che hai generato nel passaggio 1.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

    Se la richiesta ha esito positivo, non viene restituita alcuna risposta.

API XML

Questa funzionalità non può essere gestita tramite l'API XML. Usa l'API JSON.

Controlla lo stato di replica di un bucket

Per controllare l'RPO (Recovery Point Objective) o lo stato della replica di un bucket, segui queste istruzioni:

Console

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket che vuoi verificare.

  3. Fai clic sulla scheda Configuration (Configurazione).

  4. Se la replica turbo è abilitata nel bucket, la replica è impostata su Turbo.

Riga di comando

gcloud

Utilizza il comando gcloud storage buckets describe con il flag --format:

gcloud storage buckets describe gs://BUCKET_NAME --format="default(rpo)"

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

In caso di esito positivo, la risposta avrà il seguente esempio:

rpo: ASYNC_TURBO

gsutil

Utilizza il comando gsutil rpo get:

gsutil rpo get gs://BUCKET_NAME/

Dove:

  • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

In caso di esito positivo, la risposta avrà il seguente esempio:

gs://my-bucket: ASYNC_TURBO

Librerie client

C++

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage C++.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  auto metadata = client.GetBucketMetadata(bucket_name);
  if (!metadata) throw std::move(metadata).status();

  std::cout << "RPO is " << metadata->rpo() << " for bucket "
            << metadata->name() << "\n";
}

C#

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage C#.


using System;
using Google.Cloud.Storage.V1;

public class GetRpoSample
{
    public string GetRpo(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var rpo = storage.GetBucket(bucketName).Rpo;
        Console.WriteLine($"The RPO Setting of bucket {bucketName} is {rpo}.");

        return rpo;
    }
}

Go

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Go.

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

	"cloud.google.com/go/storage"
)

// getRPO gets the current RPO (Recovery Point Objective) setting
// for the bucket, either "DEFAULT" or "ASYNC_TURBO".
func getRPO(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %v", bucketName, err)
	}
	fmt.Fprintf(w, "RPO is %s for %v", attrs.RPO, bucketName)
	return nil
}

Java

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Java.

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class GetBucketRpo {
  public static void getBucketRpo(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    String rpo = bucket.getRpo().toString();

    System.out.println("The RPO setting of bucket " + bucketName + " is " + rpo);
  }
}

Node.js

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Node.js.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The name of your GCS bucket in a dual-region
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getRPO() {
  // Gets Bucket Metadata and prints RPO value (either 'default' or 'async_turbo').
  // If RPO is undefined, the bucket is a single region bucket
  const [metadata] = await storage.bucket(bucketName).getMetadata();
  console.log(`RPO is ${metadata.rpo} for ${bucketName}.`);
}

getRPO();

PHP

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage PHP.

use Google\Cloud\Storage\StorageClient;

/**
 * Get the bucket's recovery point objective (RPO) setting.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_rpo(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    printf(
        'The bucket\'s RPO value is: %s.' . PHP_EOL,
        $bucket->info()['rpo']
    );
}

Python

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Python.


from google.cloud import storage
from google.cloud.storage.constants import RPO_DEFAULT

def get_rpo(bucket_name):
    """Gets the RPO of the bucket"""
    # The ID of your GCS bucket
    # bucket_name = "my-bucket"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    bucket.rpo = RPO_DEFAULT
    rpo = bucket.rpo

    print(f"RPO for {bucket.name} is {rpo}.")

Ruby

Per ulteriori informazioni, consulta la documentazione di riferimento per l'API Cloud Storage Ruby.

def get_rpo bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  puts "The RPO setting of bucket '#{bucket_name}' is #{bucket.rpo}."
end

API REST

API JSON

  1. Richiedi un token di accesso all'autorizzazione da Playground OAuth 2.0. Configura il parco giochi in modo che utilizzi le tue credenziali OAuth. Per le istruzioni, consulta Autenticazione API.
  2. Usa cURL per chiamare l'API JSON con una richiesta GET Bucket:

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=rpo"

    Dove:

    • OAUTH2_TOKEN è il nome del token di accesso che hai generato nel passaggio 1.
    • BUCKET_NAME è il nome del bucket pertinente. Ad esempio, my-bucket.

    La risposta sarà simile all'esempio seguente:

    {
      "name": "my-bucket",
      "projectNumber": "234...",
      ...
      "rpo": "ASYNC_TURBO"
    }

    Nota la chiave rpo. Il valore ASYNC_TURBO indica che la replica turbo è abilitata. DEFAULT indica che viene applicata la replica predefinita. Il campo rpo è sempre presente per i bucket a doppia e in più aree geografiche, ma è assente dai bucket a singola area geografica.

API XML

Questa funzionalità non può essere gestita tramite l'API XML. Usa l'API JSON.

Monitora le prestazioni di replica turbo di un bucket

  1. Nella console Google Cloud, vai alla pagina Bucket di Cloud Storage.

    Vai a Bucket

  2. Nell'elenco dei bucket, fai clic sul nome del bucket desiderato.

  3. Fai clic sulla scheda Configuration (Configurazione).

  4. Nella riga Replica, fai clic su Visualizza metriche di replica.

    Se la replica di un oggetto richiede più di 15 minuti, i minuti supplementari vengono aggregati e visualizzati nella console Google Cloud come Numero di minuti mancanti RPO. La console Google Cloud monitora anche il numero di repliche di oggetti completate, mostrate come repliche di oggetti con turbo.

    Per saperne di più, consulta Monitoraggio delle prestazioni della replica Turbo.

Passaggi successivi