Administra la replicación turbo

Descripción general

En esta página, se describe cómo usar la función de replicación turbo en un bucket de doble región.

Permisos necesarios

Console

Para completar esta guía con la consola de Google Cloud, debes tener los permisos de IAM adecuados. Para usar esta función, debes tener un bucket en una ubicación birregional o tener la intención de crear uno. Si el bucket al que deseas acceder para transmitir existe en un proyecto que no creaste, tal vez necesites que el propietario del proyecto te otorgue un rol con los permisos necesarios.

A fin de obtener una lista de los permisos necesarios para acciones específicas, consulta Permisos de IAM para la consola de Google Cloud.

Para obtener una lista de los roles relevantes, consulta Funciones de Cloud Storage. Como alternativa, puedes crear un rol personalizado que tenga permisos más limitados.

Línea de comandos

Para completar esta guía con una utilidad de línea de comandos, debes tener los permisos de IAM adecuados. Para usar esta función, debes tener un bucket en una ubicación birregional o tener la intención de crear uno. Si el bucket al que deseas acceder para transmitir existe en un proyecto que no creaste, tal vez necesites que el propietario del proyecto te otorgue un rol con los permisos necesarios.

Si deseas obtener una lista de los permisos necesarios para acciones específicas, consulta Permisos de IAM para los comandos de gcloud storage.

Para obtener una lista de los roles relevantes, consulta Funciones de Cloud Storage. Como alternativa, puedes crear un rol personalizado que tenga permisos más limitados.

Bibliotecas cliente

Para completar esta guía con las bibliotecas cliente de Cloud Storage, debes tener los permisos de IAM adecuados. Para usar esta función, debes tener un bucket en una ubicación birregional o tener la intención de crear uno. Si el bucket al que deseas acceder para transmitir existe en un proyecto que no creaste, tal vez necesites que el propietario del proyecto te otorgue un rol con los permisos necesarios.

A menos que se indique lo contrario, las solicitudes de la biblioteca cliente se realizan mediante la API de JSON y requieren permisos, como se indica en Permisos de IAM para métodos de JSON. Para ver qué métodos de la API de JSON se invocan cuando realizas solicitudes a través de una biblioteca cliente, registra las solicitudes sin procesar.

Para obtener una lista de los roles de IAM relevantes, consulta Roles de Cloud Storage. Como alternativa, puedes crear un rol personalizado que tenga permisos más limitados.

APIs de REST

API de JSON

Para completar esta guía con la API de JSON, debes tener los permisos de IAM adecuados. Para usar esta función, debes tener un bucket en una ubicación birregional o tener la intención de crear uno. Si el bucket al que deseas acceder para transmitir existe en un proyecto que no creaste, tal vez necesites que el propietario del proyecto te otorgue un rol con los permisos necesarios.

Si deseas obtener una lista de los permisos necesarios para acciones específicas, consulta Permisos de IAM para métodos JSON.

Para obtener una lista de los roles relevantes, consulta Funciones de Cloud Storage. Como alternativa, puedes crear un rol personalizado que tenga permisos más limitados.

API de XML

Esta función no se puede administrar a través de la API de XML. En su lugar, usa la API de JSON.

Configurar la replicación turbo

Para habilitar o inhabilitar la replicación turbo en un bucket existente, completa las siguientes instrucciones:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket deseado.

  3. Haz clic en la pestaña Configuración.

  4. En la fila Replicación, haz clic en Editar.

    La ventana que aparece indica si estás a punto de Habilitar la replicación turbo o Inhabilitar la replicación turbo.

  5. Haz clic en Guardar para confirmar la configuración nueva.

Línea de comandos

Usa el comando gcloud storage buckets update con la marca --rpo:

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

Aquí:

  • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

  • STATE es ASYNC_TURBO cuando se habilita la replicación turbo o DEFAULT cuando se inhabilita.

Si se ejecuta de forma correcta, la respuesta se ve de la siguiente manera:

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

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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";
}

En el siguiente ejemplo, se habilita la replicación predeterminada en 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#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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}");
    }
}

En el siguiente ejemplo, se habilita la replicación predeterminada en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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: %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
}

En el siguiente ejemplo, se habilita la replicación predeterminada en 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: %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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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);
  }
}

En el siguiente ejemplo, se habilita la replicación predeterminada en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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));

En el siguiente ejemplo, se habilita la replicación predeterminada en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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);

En el siguiente ejemplo, se habilita la replicación predeterminada en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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])

En el siguiente ejemplo, se habilita la replicación predeterminada en 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se habilita la replicación turbo en 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__

En el siguiente ejemplo, se habilita la replicación predeterminada en 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 de REST

API de JSON

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Crea un archivo JSON que contenga la siguiente información:

    {
      "rpo": "STATE"
    }

    En el ejemplo anterior, STATE es ASYNC_TURBO cuando se habilita la replicación turbo o DEFAULT cuando se inhabilita.

  3. Usa cURL para llamar a la API de JSON con una solicitud de 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"

    Dónde:

    • JSON_FILE_NAME es la ruta de acceso del archivo JSON que creaste en el paso 2.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

    Si la solicitud se realiza correctamente, no se mostrará ninguna respuesta.

API de XML

Esta función no se puede administrar a través de la API de XML. En su lugar, usa la API de JSON.

Comprueba el estado de replicación de un bucket

Para verificar el objetivo de punto de recuperación (RPO) o el estado de replicación de un bucket, completa las siguientes instrucciones:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket que deseas verificar.

  3. Haz clic en la pestaña Configuración.

  4. Si la replicación turbo está habilitada en el bucket, la replicación se establece en Turbo.

Línea de comandos

Usa el comando gcloud storage buckets describe con la marca --format:

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

Dónde:

  • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket

Si se ejecuta de forma correcta, la respuesta se parece al siguiente ejemplo:

rpo: ASYNC_TURBO

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo 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

API de REST

API de JSON

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Usa cURL para llamar a la API de JSON con una solicitud de bucket GET:

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

    Aquí:

    • OAUTH2_TOKEN es el nombre del token de acceso que generaste en el paso 1.
    • BUCKET_NAME es el nombre del bucket correspondiente. Por ejemplo, my-bucket.

    La respuesta se ve como el siguiente ejemplo:

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

    Observa la clave rpo. El valor ASYNC_TURBO indica que la replicación turbo está habilitada. DEFAULT indica que se aplica la replicación predeterminada. El campo rpo siempre está presente para buckets multirregionales y de región doble, pero está ausente en los buckets de una sola región.

API de XML

Esta función no se puede administrar a través de la API de XML. En su lugar, usa la API de JSON.

¿Qué sigue?