A replicação de dados copia objetos e suas operações de criação, atualização e exclusão de um bucket de origem para um bucket de destino de forma assíncrona e em tempo quase real. O OSS oferece suporte à replicação entre regiões (CRR) e à replicação na mesma região (SRR).
Observações
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber mais sobre como configurar credenciais de acesso, consulte Configurar credenciais de acesso (Python SDK V1).
Este exemplo demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Inicialização.
Para ativar a replicação de dados, é necessária a permissão
oss:PutBucketReplication. Para consultar regras de replicação, utilize a permissãooss:GetBucketReplication. Para listar as regiões de destino disponíveis, aplique a permissãooss:GetBucketReplicationLocation. O acompanhamento do progresso da tarefa exige a permissãooss:GetBucketReplicationProgress, enquanto a desativação requeross:DeleteBucketReplication. Para detalhes adicionais, consulte Conceder uma política personalizada.
Ativar a replicação de dados
Antes de ativar a replicação de dados, verifique se os buckets de origem e de destino estão ambos sem versionamento ou com o versionamento ativado.
O código a seguir ativa a replicação de dados do srcexamplebucket na região China (Hangzhou) para o destexamplebucket na mesma região ou em outra.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
replica_config = ReplicationRule(
# Specify the destination bucket to which you want to replicate data.
target_bucket_name='destexamplebucket',
# Specify the region where the destination bucket is located.
# If you want to enable cross-region replication, the source and destination buckets must be in different regions. If you want to enable same-region replication, the source and destination buckets must be in the same region.
target_bucket_location='yourTargetBucketLocation'
)
# Specify the prefixes of the objects to replicate. After you specify prefixes, only objects that match the prefixes are replicated to the destination bucket.
# prefix_list = ['prefix1', 'prefix2']
# Set the data replication rule.
# replica_config = ReplicationRule(
# prefix_list=prefix_list,
# Replicate object creation and update operations in the source bucket to the destination bucket.
# action_list=[ReplicationRule.PUT],
# Specify the destination bucket to which you want to replicate data.
# target_bucket_name='destexamplebucket1',
# Specify the region where the destination bucket is located.
# target_bucket_location='yourTargetBucketLocation',
# By default, historical data is replicated. In this example, this parameter is set to False to disable historical data replication.
# is_enable_historical_object_replication=False,
# Specify the data transmission link for data replication.
# target_transfer_type='oss_acc',
# Specify the role that OSS is authorized to use for data replication. This element is required if you use SSE-KMS to encrypt destination objects.
# sync_role_name='roleNameTest',
# Replicate objects that are created with SSE-KMS encryption.
# sse_kms_encrypted_objects_status=ReplicationRule.ENABLED
# Specify the SSE-KMS key ID. This element is required if you replicate objects that are created with SSE-KMS encryption.
# replica_kms_keyid='9468da86-3509-4f8d-a61e-6eab1eac****',
#)
# Enable data replication.
bucket.put_bucket_replication(replica_config)
Visualizar regras de replicação de dados
O código a seguir consulta as regras de replicação de dados do examplebucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# View the data replication rules.
result = bucket.get_bucket_replication()
# Print the returned information.
for rule in result.rule_list:
print(rule.rule_id)
print(rule.target_bucket_name)
print(rule.target_bucket_location)
Visualizar regiões de destino disponíveis para replicação
O código a seguir lista as regiões de destino para onde os dados do examplebucket podem ser replicados.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# View the destination regions available for replication.
result = bucket.get_bucket_replication_location()
for location in result.location_list:
print(location)
Visualizar o progresso da replicação de dados
É possível consultar o andamento das tarefas de replicação de dados históricos e incrementais.
O progresso da replicação de dados históricos é expresso em porcentagem. Essa consulta só está disponível para buckets com a replicação histórica ativada.
O progresso da replicação incremental aparece como um ponto no tempo, indicando que todos os dados armazenados antes desse momento já foram copiados.
O código a seguir verifica o status da replicação para a regra com ID test_replication_1 no examplebucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# View the data replication progress.
# Specify the replication rule ID, for example, test_replication_1.
result = bucket.get_bucket_replication_progress('test_replication_1')
print(result.progress.rule_id)
# Check whether historical data replication is enabled.
print(result.progress.is_enable_historical_object_replication)
# Historical data replication progress.
print(result.progress.historical_object_progress)
# Real-time data replication progress.
print(result.progress.new_object_progress)
Desativar a replicação de dados
Para interromper a replicação entre um bucket de origem e outro de destino, exclua a regra correspondente.
O código a seguir remove a regra de replicação identificada por test_replication_1 do examplebucket.
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import ReplicationRule
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the region information that corresponds to the endpoint, for example, cn-hangzhou. Note that this parameter is required for V4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "examplebucket", region=region)
# Disable data replication. After this operation, replicated objects remain in the destination bucket, but new changes from the source bucket stop replicating.
# Specify the replication rule ID, for example, test_replication_1.
result = bucket.delete_bucket_replication('test_replication_1')
Referências
Para acessar o código completo de exemplo sobre replicação de dados, visite o GitHub.
Para obter mais informações sobre a operação de API para ativar a replicação, consulte PutBucketReplication.
Para obter mais informações sobre a operação de API para visualizar regras de replicação, consulte GetBucketReplication.
Para obter mais informações sobre a operação de API para visualizar regiões de destino disponíveis para replicação, consulte GetBucketReplicationLocation.
Para obter mais informações sobre a operação de API para visualizar o progresso da replicação, consulte GetBucketReplicationProgress.
Para obter mais informações sobre a operação de API para desativar a replicação, consulte DeleteBucketReplication.