Como gerenciar a replicação turbo

Visão geral

Nesta página, você verá como usar o recurso de replicação turbo em um bucket birregional.

Permissões necessárias

Console

Para concluir este guia usando o Console do Google Cloud, é preciso ter as permissões de IAM adequadas. Para usar esse recurso, você precisa ter ou criar um bucket em um local birregional. Se o bucket que você quer acessar para streaming existir em um projeto que você não criou, talvez seja necessário que o proprietário do projeto conceda um papel que contenha as permissões necessárias.

Para uma lista de permissões necessárias para ações específicas, consulte Permissões do IAM para o Console do Google Cloud.

Para ver a lista de papéis relevantes, consulte Papéis do Cloud Storage. Como alternativa, é possível criar um papel personalizado que tenha permissões mais limitadas.

Linha de comando

Para concluir este guia usando um utilitário de linha de comando, você precisa ter as permissões de IAM adequadas. Para usar esse recurso, você precisa ter ou criar um bucket em um local birregional. Se o bucket que você quer acessar para streaming existir em um projeto que você não criou, talvez seja necessário que o proprietário do projeto conceda um papel que contenha as permissões necessárias.

Para uma lista de permissões necessárias para ações específicas, consulte Permissões do IAM para comandos gcloud storage.

Para ver a lista de papéis relevantes, consulte Papéis do Cloud Storage. Como alternativa, é possível criar um papel personalizado que tenha permissões mais limitadas.

Bibliotecas de cliente

Para concluir este guia usando as bibliotecas de cliente do Cloud Storage, é preciso ter as permissões de IAM adequadas. Para usar esse recurso, você precisa ter ou criar um bucket em um local birregional. Se o bucket que você quer acessar existir em um projeto que você não criou, talvez seja necessário que o proprietário do projeto conceda um papel que contenha as permissões necessárias.

A menos que indicado de outra forma, as solicitações da biblioteca de cliente são feitas por meio da API JSON e exigem permissões conforme listado em Permissões do IAM para métodos JSON. Para conferir quais métodos da API JSON são invocados ao fazer solicitações usando uma biblioteca de cliente, registre as solicitações brutas.

Para conferir a lista de papéis do IAM relevantes, consulte Papéis do Cloud Storage. Como alternativa, é possível criar um papel personalizado que tenha permissões mais limitadas.

APIs REST

API JSON

Para concluir este guia usando a API JSON, é preciso ter as permissões do IAM adequadas. Para usar esse recurso, você precisa ter ou criar um bucket em um local birregional. Se o bucket que você quer acessar existir em um projeto que você não criou, talvez seja necessário que o proprietário do projeto conceda um papel que contenha as permissões necessárias.

Para uma lista de permissões necessárias para ações específicas, consulte Permissões do IAM para métodos JSON.

Para ver a lista de papéis relevantes, consulte Papéis do Cloud Storage. Como alternativa, é possível criar um papel personalizado que tenha permissões mais limitadas.

API XML

Esse recurso não pode ser gerenciado pela API XML. Use a API JSON.

Definir a replicação turbo

Para ativar ou desativar a replicação turbo em um bucket atual, conclua as instruções a seguir:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome do bucket pretendido.

  3. Clique na guia Configuração.

  4. Na linha Replicação, clique em Editar.

    A janela exibida indica se você está prestes a Ativar a replicação turbo ou Desativar a replicação turbo.

  5. Clique em Salvar para confirmar a nova configuração.

Linha de comando

Use o comando gcloud storage buckets update com a flag --rpo:

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

Em que:

  • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

  • STATE é ASYNC_TURBO para ativar a replicação turbo ou DEFAULT para desativar a replicação turbo.

Se bem-sucedida, a resposta terá esta aparência:

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

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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";
}

O exemplo a seguir ativa a replicação padrão em um 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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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}");
    }
}

O exemplo a seguir ativa a replicação padrão em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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: %w", 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: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication enabled for %v", bucketName)
	return nil
}

O exemplo a seguir ativa a replicação padrão em um 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: %w", 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: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Turbo replication disabled for %v", bucketName)
	return nil
}

Java

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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);
  }
}

O exemplo a seguir ativa a replicação padrão em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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));

O exemplo a seguir ativa a replicação padrão em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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);

O exemplo a seguir ativa a replicação padrão em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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])

O exemplo a seguir ativa a replicação padrão em um 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

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

O exemplo a seguir ativa a replicação turbo em um 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__

O exemplo a seguir ativa a replicação padrão em um 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__

APIs REST

API JSON

  1. Receba um token de acesso de autorização do OAuth 2.0 Playground. Configure o Playground para usar suas credenciais do OAuth. Para ver instruções, consulte Autenticação de APIs.
  2. Crie um arquivo JSON com as informações a seguir:

    {
      "rpo": "STATE"
    }

    Em que STATE é ASYNC_TURBO para ativar a replicação turbo ou DEFAULT para desativar a replicação turbo.

  3. Use cURL para chamar a API JSON com uma solicitação bucket PATCH:

    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"

    Em que:

    • JSON_FILE_NAME é o caminho para o arquivo JSON criado na Etapa 2.
    • OAUTH2_TOKEN é o token de acesso gerado na Etapa 1.
    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

    Se a solicitação for bem-sucedida, nenhuma resposta será retornada.

API XML

Esse recurso não pode ser gerenciado pela API XML. Use a API JSON.

Verificar o status da replicação de um bucket

Para verificar o objetivo do ponto de recuperação (RPO, na sigla em inglês) ou o status de replicação de um bucket, conclua estas instruções:

Console

  1. No Console do Google Cloud, acesse a página Buckets do Cloud Storage.

    Acessar buckets

  2. Na lista de buckets, clique no nome do bucket que você quer verificar.

  3. Clique na guia Configuração.

  4. Se a replicação turbo estiver ativada no bucket, Replicação estará definida como Turbo.

Linha de comando

Use o comando gcloud storage buckets describe com a flag --format:

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

Em que:

  • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

Se funcionar, a resposta será parecida com esta:

rpo: ASYNC_TURBO

Bibliotecas de cliente

C++

Para mais informações, consulte a documentação de referência da API Cloud Storage C++.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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#

Para mais informações, consulte a documentação de referência da API Cloud Storage C#.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


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

Para mais informações, consulte a documentação de referência da API Cloud Storage Go.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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: %w", 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: %w", bucketName, err)
	}
	fmt.Fprintf(w, "RPO is %s for %v", attrs.RPO, bucketName)
	return nil
}

Java

Para mais informações, consulte a documentação de referência da API Cloud Storage Java.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para mais informações, consulte a documentação de referência da API Cloud Storage Node.js.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * 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

Para mais informações, consulte a documentação de referência da API Cloud Storage PHP.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

Para mais informações, consulte a documentação de referência da API Cloud Storage Python.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


from google.cloud import storage


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.get_bucket(bucket_name)
    rpo = bucket.rpo

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

Ruby

Para mais informações, consulte a documentação de referência da API Cloud Storage Ruby.

Para autenticar no Cloud Storage, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

APIs REST

API JSON

  1. Receba um token de acesso de autorização do OAuth 2.0 Playground. Configure o Playground para usar suas credenciais do OAuth. Para ver instruções, consulte Autenticação de APIs.
  2. Use cURL (em inglês) para chamar a API JSON com uma solicitação GET Bucket:

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

    Em que:

    • OAUTH2_TOKEN é o nome do token de acesso que você gerou na etapa 1.
    • BUCKET_NAME é o nome do bucket pertinente. Por exemplo, my-bucket.

    A resposta terá esta aparência:

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

    Observe a chave rpo. O valor ASYNC_TURBO indica que a replicação turbo está ativada. DEFAULT indica que a replicação padrão foi aplicada. O campo rpo está sempre presente para buckets de duas e várias regiões, mas está ausente em buckets de região única.

API XML

Esse recurso não pode ser gerenciado pela API XML. Use a API JSON.

A seguir