O OSS Tables executa automaticamente compactação, gerenciamento de snapshots e limpeza de arquivos não referenciados para otimizar o desempenho de consultas e reduzir custos de armazenamento. Não são necessários recursos computacionais externos.
A manutenção automática executa três tarefas em níveis diferentes de recursos:
Limpeza de arquivos não referenciados: Configurada no nível do bucket. Identifica e exclui automaticamente objetos que nenhum snapshot de tabela referencia.
Compactação: Configurada no nível da tabela. Mescla arquivos pequenos em arquivos maiores para melhorar o desempenho das consultas.
Gerenciamento de snapshots: Configurado no nível da tabela. Limpa automaticamente snapshots expirados para reduzir arquivos de metadados e sobrecarga de armazenamento.
Os seguintes padrões se aplicam ao criar um bucket ou uma tabela.
|
Recurso de manutenção |
Nível de configuração |
Parâmetro |
Padrão |
|
Limpeza de arquivos não referenciados |
nível do bucket |
status |
enabled |
|
unreferencedDays |
3 |
||
|
nonCurrentDays |
10 |
||
|
Compactação |
nível da tabela |
status |
enabled |
|
targetFileSizeMB |
512 |
||
|
strategy |
auto |
||
|
Gerenciamento de snapshots |
nível da tabela |
status |
enabled |
|
maxSnapshotAgeHours |
120 |
||
|
minSnapshotsToKeep |
1 |
Função vinculada ao serviço
Um serviço em segundo plano executa a manutenção automática (compactação, limpeza de arquivos não referenciados e gerenciamento de snapshots) para o OSS Tables. Ele utiliza a função vinculada ao serviço AliyunServiceRoleForOssTableMaintenance para acessar Table Buckets.
Autorização
Ao abrir a página Table Buckets no console do OSS pela primeira vez, uma notificação aparecerá caso a função vinculada ao serviço ainda não tenha sido criada: Missing permissions: AliyunServiceRoleForOssTableMaintenance. Clique em Create Now para criar a função. O serviço de manutenção em segundo plano inicia automaticamente após a criação da função.
Se você for um usuário RAM, certifique-se de ter permissão para criar funções vinculadas ao serviço. Anexe a seguinte política ao usuário RAM:
{
"Version": "1",
"Statement": [
{
"Action": "ram:CreateServiceLinkedRole",
"Resource": "*",
"Effect": "Allow",
"Condition": {
"StringEquals": {
"ram:ServiceName": "tablemaintenance.oss.aliyuncs.com"
}
}
}
]
}
Permissões
A política de permissões (AliyunServiceRolePolicyForOssTableMaintenance) concede as seguintes permissões:
|
Ação |
Descrição |
|
oss:GetTableBucketMaintenanceConfiguration |
Ler configurações de manutenção no nível do bucket |
|
oss:GetTableMaintenanceConfiguration |
Ler configurações de manutenção no nível da tabela |
|
oss:ListTableBuckets |
Listar Table Buckets |
|
oss:GetTableBucket |
Obter informações do Table Bucket |
|
oss:ListTables |
Listar tabelas |
|
oss:GetTable |
Obter informações da tabela |
|
oss:GetTableData |
Ler arquivos de dados da tabela (para compactar e limpar) |
|
oss:PutTableData |
Gravar arquivos de dados da tabela (para gerar novos arquivos após a compactação) |
|
oss:GetTableMetadataLocation |
Obter a localização do arquivo de metadados |
|
oss:UpdateTableMetadataLocation |
Atualizar a localização do arquivo de metadados (para confirmar alterações após a manutenção) |
Limpeza de arquivos não referenciados
A limpeza de arquivos não referenciados é uma otimização de nível de bucket aplicada a todas as tabelas em um Table Bucket. Ela exclui arquivos de dados (Parquet, Avro ou ORC) que nenhum snapshot de tabela referencia. Esses arquivos órfãos podem se acumular devido a falhas em jobs de gravação ou snapshots expirados, consumindo armazenamento desnecessário.
Quando ativada, a limpeza de arquivos não referenciados também exclui arquivos Parquet, Avro ou ORC no Table Bucket que não fazem parte de nenhuma tabela.
A limpeza utiliza um processo de dois estágios: primeiro, os arquivos são marcados como não atuais (controlado por unreferencedDays) e depois excluídos após permanecerem como não atuais pelo período especificado (controlado por nonCurrentDays).
Parâmetros de configuração:
|
Parâmetro |
Descrição |
Valor |
Padrão |
|
status |
Ativa ou desativa a limpeza de arquivos não referenciados. |
enabled ou disabled. |
enabled |
|
unreferencedDays |
Dias antes de marcar um arquivo não referenciado como não atual. |
1 a 2147483647. |
3 |
|
nonCurrentDays |
Dias antes de excluir um arquivo não atual. |
1 a 2147483647. |
10 |
Console
Visualize e modifique a configuração de manutenção de um Table Bucket no console do OSS.
Siga estas etapas:
Faça login no console do OSS. No painel de navegação à esquerda, escolha Table Bucket List.
Clique no nome do Table Bucket para abrir sua página de detalhes.
Escolha a aba Data Maintenance.
-
Na seção Unreferenced File Cleanup, visualize a configuração atual:
Status: Indica se o recurso está ativado.
Unreferenced Days: Dias antes de marcar um arquivo não referenciado como não atual. Padrão: 3.
Non-current Days: Dias antes de excluir um arquivo não atual. Padrão: 10.
Clique em Edit, modifique os parâmetros de limpeza de arquivos não referenciados e clique em Save.
ossutil
Use o ossutil para modificar a configuração de limpeza de arquivos não referenciados:
ossutil tables-api put-table-bucket-maintenance-configuration \
--table-bucket-arn {ARN} \
--type icebergUnreferencedFileRemoval \
--value '{"status":"enabled","settings":{"icebergUnreferencedFileRemoval":{"unreferencedDays":5,"nonCurrentDays":15}}}'
SDK
Consulte e modifique a configuração de limpeza de arquivos não referenciados usando um SDK.
Python
Consulte a configuração de limpeza de arquivos não referenciados:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="get table bucket maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
result = client.get_table_bucket_maintenance_configuration(
oss_tables.models.GetTableBucketMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' table bucket arn: {result.table_bucket_arn},'
f' configuration: {result.configuration}')
if __name__ == "__main__":
main()
Modifique a configuração de limpeza de arquivos não referenciados:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="put table bucket maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--type', help='The maintenance type, e.g., icebergUnreferencedFileRemoval.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
value = {
'status': 'enabled',
'settings': {
'icebergUnreferencedFileRemoval': {
'unreferencedDays': 7,
'nonCurrentDays': 30
}
}
}
result = client.put_table_bucket_maintenance_configuration(
oss_tables.models.PutTableBucketMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
type=args.type,
value=value,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id}')
print(f'successfully updated maintenance configuration for: {args.table_bucket_arn}')
if __name__ == "__main__":
main()
Go
Consulte a configuração de limpeza de arquivos não referenciados:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
}
func main() {
flag.Parse()
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
result, err := client.GetTableBucketMaintenanceConfiguration(context.TODO(), &tables.GetTableBucketMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
})
if err != nil {
log.Fatalf("failed to get table bucket maintenance configuration %v", err)
}
log.Printf("get table bucket maintenance configuration result:%#v\n", result)
}
Modifique a configuração de limpeza de arquivos não referenciados:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
}
func main() {
flag.Parse()
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
result, err := client.PutTableBucketMaintenanceConfiguration(context.TODO(), &tables.PutTableBucketMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Type: oss.Ptr("icebergUnreferencedFileRemoval"),
Value: &tables.MaintenanceValue{
Settings: &tables.MaintenanceSettings{
IcebergUnreferencedFileRemoval: &tables.SettingsDetail{
UnreferencedDays: oss.Ptr(4),
NonCurrentDays: oss.Ptr(10),
},
},
Status: oss.Ptr("enabled"),
},
})
if err != nil {
log.Fatalf("failed to put table bucket maintenance configuration %v", err)
}
log.Printf("put table bucket maintenance configuration result:%#v\n", result)
}
Java
Consulte a configuração de limpeza de arquivos não referenciados:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class GetTableBucketMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
GetTableBucketMaintenanceConfigurationRequest request = GetTableBucketMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.build();
GetTableBucketMaintenanceConfigurationResult result = client.getTableBucketMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Successfully got maintenance configuration for table bucket: %s%n", tableBucketARN);
System.out.printf("Table Bucket ARN: %s%n", result.tableBucketARN());
result.configuration().forEach((key, value) -> {
System.out.printf("Configuration Type: %s, Status: %s%n", key, value.status());
});
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Modifique a configuração de limpeza de arquivos não referenciados:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class PutTableBucketMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String type = "icebergUnreferencedFileRemoval";
String status = "enabled";
int unreferencedDays = 3;
int nonCurrentDays = 3;
IcebergUnreferencedFileRemovalSettings removalSettings = IcebergUnreferencedFileRemovalSettings.newBuilder()
.unreferencedDays(unreferencedDays)
.nonCurrentDays(nonCurrentDays)
.build();
TableBucketMaintenanceSettings settings = TableBucketMaintenanceSettings.newBuilder()
.icebergUnreferencedFileRemoval(removalSettings)
.build();
TableBucketMaintenanceConfigurationValue value = TableBucketMaintenanceConfigurationValue.newBuilder()
.status(status)
.settings(settings)
.build();
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
PutTableBucketMaintenanceConfigurationRequest request = PutTableBucketMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.type(type)
.value(value)
.build();
PutTableBucketMaintenanceConfigurationResult result = client.putTableBucketMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Successfully configured maintenance for table bucket: %s%n", tableBucketARN);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
API
Use as seguintes operações de API:
Consultar configuração: GetTableBucketMaintenanceConfiguration
Modificar configuração: PutTableBucketMaintenanceConfiguration
Compactação
A compactação é uma otimização de nível de tabela. Gravações frequentes em streaming ou em pequenos lotes em tabelas Apache Iceberg podem gerar muitos arquivos pequenos, o que degrada o desempenho das consultas. A compactação mescla arquivos pequenos em arquivos maiores que se aproximam de um tamanho alvo, reduzindo a contagem de arquivos e a sobrecarga de metadados.
Parâmetros de configuração:
|
Parâmetro |
Descrição |
Valor |
Padrão |
|
status |
Ativa ou desativa a compactação automática. |
enabled ou disabled |
enabled |
|
targetFileSizeMB |
Tamanho alvo do arquivo (MB) após a compactação. Arquivos menores que este valor são mesclados. |
1 a 2147483647. |
512 |
|
strategy |
Estratégia de compactação que determina como os arquivos são mesclados e ordenados. |
auto, binpack, sort ou z-order. Se você definir este parâmetro como sort ou z-order, uma ordem de classificação deve estar definida nos metadados da tabela. |
auto |
Estratégias disponíveis:
auto: O sistema seleciona automaticamente a estratégia ideal de compactação. Aplica a estratégia sort para tabelas com ordem de classificação definida e a estratégia binpack para tabelas sem essa definição.
binpack: Mescla arquivos baseando-se apenas no tamanho, sem alterar a ordem dos dados. Esta é a estratégia mais rápida e adequada quando a ordenação de dados não é necessária.
sort: Ordena e mescla dados com base na ordem de classificação definida na tabela. Recomendada para cenários de consulta por intervalo. Uma ordem de classificação deve estar definida nos metadados da tabela.
z-order: Utiliza uma curva Z-Order para ordenar e mesclar dados em várias colunas simultaneamente. Projetada para cenários de consulta multidimensional. Uma ordem de classificação deve estar definida nos metadados da tabela.
Visualize e configure a compactação:
Console
Visualize e modifique as configurações de compactação na aba Data Maintenance.
Faça login no console do OSS. No painel de navegação à esquerda, escolha Table Bucket List.
Clique no nome do Table Bucket desejado. Na Table list, clique no nome da tabela alvo para abrir a página de detalhes da tabela.
Selecione a aba Data Maintenance.
-
Na seção Compaction, visualize a configuração atual:
Status: Indica se a compactação automática está ativada.
Target file size: Tamanho alvo para cada arquivo após a compactação. Padrão: 512 MB.
Compaction strategy: Estratégia de compactação ativa. Padrão: auto.
Job status: Status e carimbo de data/hora do último job de compactação.
Clique em Edit, modifique os parâmetros de compactação e clique em Save.
ossutil
Use o ossutil para modificar a configuração de compactação:
ossutil tables-api put-table-maintenance-configuration \
--table-bucket-arn {ARN} \
--namespace mynamespace \
--name mytable \
--type icebergCompaction \
--value '{"status":"enabled","settings":{"icebergCompaction":{"targetFileSizeMB":256,"strategy":"binpack"}}}'
SDK
Consulte e modifique a configuração de compactação usando um SDK.
Python
Consulte a configuração de compactação:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="get table maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--namespace', help='The namespace of the table.', required=True)
parser.add_argument('--name', help='The name of the table.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
result = client.get_table_maintenance_configuration(
oss_tables.models.GetTableMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
namespace=args.namespace,
name=args.name,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' table arn: {result.table_arn},'
f' configuration: {result.configuration}')
if __name__ == "__main__":
main()
Modifique a configuração de compactação:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="put table maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--namespace', help='The namespace of the table.', required=True)
parser.add_argument('--name', help='The name of the table.', required=True)
parser.add_argument('--type', help='The maintenance type, e.g., icebergCompaction.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
value = {
'status': 'enabled',
'settings': {
'icebergCompaction': {
'targetFileSizeMB': 512,
'strategy': 'auto'
}
}
}
result = client.put_table_maintenance_configuration(
oss_tables.models.PutTableMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
namespace=args.namespace,
name=args.name,
type=args.type,
value=value,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id}')
print(f'successfully updated maintenance configuration for: {args.namespace}/{args.name}')
if __name__ == "__main__":
main()
Go
Consulte a configuração de compactação:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
namespace string
name string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
flag.StringVar(&namespace, "namespace", "", "The name of the namespace.")
flag.StringVar(&name, "name", "", "The name of the table.")
}
func main() {
flag.Parse()
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(namespace) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, namespace name required")
}
if len(name) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table name required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
result, err := client.GetTableMaintenanceConfiguration(context.TODO(), &tables.GetTableMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Namespace: oss.Ptr(namespace),
Name: oss.Ptr(name),
})
if err != nil {
log.Fatalf("failed to get table maintenance configuration %v", err)
}
log.Printf("get table maintenance configuration result:%#v\n", result)
}
Modifique a configuração de compactação:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
namespace string
name string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
flag.StringVar(&namespace, "namespace", "", "The name of the namespace.")
flag.StringVar(&name, "name", "", "The name of the table.")
}
func main() {
flag.Parse()
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(namespace) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, namespace name required")
}
if len(name) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table name required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
// icebergCompaction type
result, err := client.PutTableMaintenanceConfiguration(context.TODO(), &tables.PutTableMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Namespace: oss.Ptr(namespace),
Name: oss.Ptr(name),
Type: oss.Ptr("icebergCompaction"),
Value: &tables.TableMaintenanceValue{
Status: oss.Ptr("enabled"),
Settings: &tables.TableMaintenanceSettings{
IcebergCompaction: &tables.IcebergCompactionSettingsDetail{
TargetFileSizeMB: oss.Ptr(400),
Strategy: oss.Ptr("auto"),
},
},
},
})
// icebergSnapshotManagement type
//result, err := client.PutTableMaintenanceConfiguration(context.TODO(), &tables.PutTableMaintenanceConfigurationRequest{
// TableBucketARN: oss.Ptr(tableBucketArn),
// Namespace: oss.Ptr(namespace),
// Name: oss.Ptr(name),
// Type: oss.Ptr("icebergSnapshotManagement"),
// Value: &tables.TableMaintenanceValue{
// Status: oss.Ptr("enabled"),
// Settings: &tables.TableMaintenanceSettings{
// IcebergSnapshotManagement: &tables.IcebergSnapshotManagementSettingsDetail{
// MaxSnapshotAgeHours: oss.Ptr(350),
// MinSnapshotsToKeep: oss.Ptr(1),
// },
// },
// },
//})
if err != nil {
log.Fatalf("failed to put table maintenance configuration %v", err)
}
log.Printf("put table maintenance configuration result:%#v\n", result)
}
Java
Consulte a configuração de compactação:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class GetTableMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String namespace = "mynamespace";
String name = "mytable";
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
GetTableMaintenanceConfigurationRequest request = GetTableMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.namespace(namespace)
.name(name)
.build();
GetTableMaintenanceConfigurationResult result = client.getTableMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Table ARN: %s%n", result.tableARN());
if (result.configuration() != null && !result.configuration().isEmpty()) {
System.out.println("Maintenance configurations:");
result.configuration().forEach((type, config) -> {
System.out.printf(" Type: %s, Status: %s%n", type, config.status());
if (config.settings() != null) {
if (config.settings().icebergCompaction() != null) {
System.out.printf(" Compaction - TargetFileSizeMB: %d, Strategy: %s%n",
config.settings().icebergCompaction().targetFileSizeMB(),
config.settings().icebergCompaction().strategy());
}
if (config.settings().icebergSnapshotManagement() != null) {
System.out.printf(" SnapshotManagement - MinSnapshotsToKeep: %d, MaxSnapshotAgeHours: %d%n",
config.settings().icebergSnapshotManagement().minSnapshotsToKeep(),
config.settings().icebergSnapshotManagement().maxSnapshotAgeHours());
}
}
});
} else {
System.out.println("No maintenance configuration found.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Modifique a configuração de compactação:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class PutTableMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String namespace = "mynamespace";
String name = "mytable";
String type = "icebergCompaction";
String status = "enabled";
int targetFileSizeMB = 256;
String strategy = "auto";
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
IcebergCompactionSettings compactionSettings = IcebergCompactionSettings.newBuilder()
.targetFileSizeMB(targetFileSizeMB)
.strategy(strategy)
.build();
TableMaintenanceSettings settings = TableMaintenanceSettings.newBuilder()
.icebergCompaction(compactionSettings)
.build();
TableMaintenanceConfigurationValue value = TableMaintenanceConfigurationValue.newBuilder()
.status(status)
.settings(settings)
.build();
PutTableMaintenanceConfigurationRequest request = PutTableMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.namespace(namespace)
.name(name)
.type(type)
.value(value)
.build();
PutTableMaintenanceConfigurationResult result = client.putTableMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Successfully put table maintenance configuration for table: %s/%s, type: %s%n", namespace, name, type);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
API
Operações de API:
Consultar configuração: GetTableMaintenanceConfiguration
Modificar configuração: PutTableMaintenanceConfiguration
Gerenciamento de snapshots
O gerenciamento de snapshots é uma otimização de nível de tabela. Cada gravação em uma tabela Apache Iceberg cria um snapshot. Com o tempo, os snapshots acumulados consomem armazenamento e aumentam a sobrecarga de metadados. O gerenciamento de snapshots limpa automaticamente os snapshots expirados para reduzir custos, preservando a segurança dos dados.
Quando minSnapshotsToKeep e maxSnapshotAgeHours entram em conflito, o sistema prioriza a retenção do número mínimo de snapshots para preservar as capacidades de recuperação de dados.
Parâmetros de configuração:
|
Parâmetro |
Descrição |
Valor |
Padrão |
|
status |
Ativa ou desativa o gerenciamento de snapshots. |
enabled ou disabled. |
enabled |
|
maxSnapshotAgeHours |
Período máximo de retenção de snapshots (horas). Snapshots mais antigos são excluídos. |
1~2147483647. |
120 |
|
minSnapshotsToKeep |
Mínimo de snapshots a serem retidos, mesmo que excedam a idade máxima. |
1~2147483647. |
1 |
Visualize e configure o gerenciamento de snapshots:
Console
Visualize e modifique as configurações de gerenciamento de snapshots na aba Data Maintenance.
Faça login no console do OSS. No painel de navegação à esquerda, escolha Table Bucket List.
Clique no nome do Table Bucket desejado. Na Table List, clique no nome da tabela alvo.
Selecione a aba Data Maintenance.
-
Na seção Snapshot Management, visualize a configuração atual:
Status: Indica se o gerenciamento de snapshots está ativado.
Maximum Snapshot Retention Time: Período máximo de retenção para snapshots. Padrão: 120 horas.
Minimum Number of Snapshots to Keep: Mínimo de snapshots a serem retidos. Padrão: 1.
Job Status: Status e carimbo de data/hora do job de limpeza de snapshots mais recente.
Clique em Edit para modificar os parâmetros de gerenciamento de snapshots e clique em Save.
ossutil
Use o ossutil para modificar a configuração de gerenciamento de snapshots:
ossutil tables-api put-table-maintenance-configuration \
--table-bucket-arn {ARN} \
--namespace mynamespace \
--name mytable \
--type icebergSnapshotManagement \
--value '{"status":"enabled","settings":{"icebergSnapshotManagement":{"maxSnapshotAgeHours":72,"minSnapshotsToKeep":3}}}'
SDK
Consulte e modifique a configuração de gerenciamento de snapshots usando um SDK. O gerenciamento de snapshots e a compactação compartilham as mesmas operações de API: GetTableMaintenanceConfiguration e PutTableMaintenanceConfiguration.
Python
Consulte a configuração de gerenciamento de snapshots:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="get table maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--namespace', help='The namespace of the table.', required=True)
parser.add_argument('--name', help='The name of the table.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
result = client.get_table_maintenance_configuration(
oss_tables.models.GetTableMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
namespace=args.namespace,
name=args.name,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' table arn: {result.table_arn},'
f' configuration: {result.configuration}')
if __name__ == "__main__":
main()
Modifique a configuração de gerenciamento de snapshots:
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="put table maintenance configuration sample")
parser.add_argument('--region', help='The region in which the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--namespace', help='The namespace of the table.', required=True)
parser.add_argument('--name', help='The name of the table.', required=True)
parser.add_argument('--type', help='The maintenance type, e.g., icebergSnapshotManagement.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
value = {
'status': 'enabled',
'settings': {
'icebergSnapshotManagement': {
'maxSnapshotAgeHours': 72,
'minSnapshotsToKeep': 3
}
}
}
result = client.put_table_maintenance_configuration(
oss_tables.models.PutTableMaintenanceConfigurationRequest(
table_bucket_arn=args.table_bucket_arn,
namespace=args.namespace,
name=args.name,
type=args.type,
value=value,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id}')
print(f'successfully updated maintenance configuration for: {args.namespace}/{args.name}')
if __name__ == "__main__":
main()
Go
Consulte a configuração de gerenciamento de snapshots:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
namespace string
name string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
flag.StringVar(&namespace, "namespace", "", "The name of the namespace.")
flag.StringVar(&name, "name", "", "The name of the table.")
}
func main() {
flag.Parse()
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(namespace) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, namespace name required")
}
if len(name) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table name required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
result, err := client.GetTableMaintenanceConfiguration(context.TODO(), &tables.GetTableMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Namespace: oss.Ptr(namespace),
Name: oss.Ptr(name),
})
if err != nil {
log.Fatalf("failed to get table maintenance configuration %v", err)
}
log.Printf("get table maintenance configuration result:%#v\n", result)
}
Modifique a configuração de gerenciamento de snapshots:
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
namespace string
name string
)
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The arn of the table bucket.")
flag.StringVar(&namespace, "namespace", "", "The name of the namespace.")
flag.StringVar(&name, "name", "", "The name of the table.")
}
func main() {
flag.Parse()
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(namespace) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, namespace name required")
}
if len(name) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table name required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
// icebergSnapshotManagement type
result, err := client.PutTableMaintenanceConfiguration(context.TODO(), &tables.PutTableMaintenanceConfigurationRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Namespace: oss.Ptr(namespace),
Name: oss.Ptr(name),
Type: oss.Ptr("icebergSnapshotManagement"),
Value: &tables.TableMaintenanceValue{
Status: oss.Ptr("enabled"),
Settings: &tables.TableMaintenanceSettings{
IcebergSnapshotManagement: &tables.IcebergSnapshotManagementSettingsDetail{
MaxSnapshotAgeHours: oss.Ptr(350),
MinSnapshotsToKeep: oss.Ptr(1),
},
},
},
})
if err != nil {
log.Fatalf("failed to put table maintenance configuration %v", err)
}
log.Printf("put table maintenance configuration result:%#v\n", result)
}
Java
Consulte a configuração de gerenciamento de snapshots:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class GetTableMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String namespace = "mynamespace";
String name = "mytable";
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
GetTableMaintenanceConfigurationRequest request = GetTableMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.namespace(namespace)
.name(name)
.build();
GetTableMaintenanceConfigurationResult result = client.getTableMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Table ARN: %s%n", result.tableARN());
if (result.configuration() != null && !result.configuration().isEmpty()) {
System.out.println("Maintenance configurations:");
result.configuration().forEach((type, config) -> {
System.out.printf(" Type: %s, Status: %s%n", type, config.status());
if (config.settings() != null) {
if (config.settings().icebergCompaction() != null) {
System.out.printf(" Compaction - TargetFileSizeMB: %d, Strategy: %s%n",
config.settings().icebergCompaction().targetFileSizeMB(),
config.settings().icebergCompaction().strategy());
}
if (config.settings().icebergSnapshotManagement() != null) {
System.out.printf(" SnapshotManagement - MinSnapshotsToKeep: %d, MaxSnapshotAgeHours: %d%n",
config.settings().icebergSnapshotManagement().minSnapshotsToKeep(),
config.settings().icebergSnapshotManagement().maxSnapshotAgeHours());
}
}
});
} else {
System.out.println("No maintenance configuration found.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Modifique a configuração de gerenciamento de snapshots:
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class PutTableMaintenanceConfigurationSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String namespace = "mynamespace";
String name = "mytable";
String type = "icebergSnapshotManagement";
String status = "enabled";
int maxSnapshotAgeHours = 72;
int minSnapshotsToKeep = 3;
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
IcebergSnapshotManagementSettings snapshotManagementSettings = IcebergSnapshotManagementSettings.newBuilder()
.maxSnapshotAgeHours(maxSnapshotAgeHours)
.minSnapshotsToKeep(minSnapshotsToKeep)
.build();
TableMaintenanceSettings settings = TableMaintenanceSettings.newBuilder()
.icebergSnapshotManagement(snapshotManagementSettings)
.build();
TableMaintenanceConfigurationValue value = TableMaintenanceConfigurationValue.newBuilder()
.status(status)
.settings(settings)
.build();
PutTableMaintenanceConfigurationRequest request = PutTableMaintenanceConfigurationRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.namespace(namespace)
.name(name)
.type(type)
.value(value)
.build();
PutTableMaintenanceConfigurationResult result = client.putTableMaintenanceConfiguration(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Successfully put table maintenance configuration for table: %s/%s, type: %s%n", namespace, name, type);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
API
Operações de API:
Consultar configuração: GetTableMaintenanceConfiguration
Modificar configuração: PutTableMaintenanceConfiguration
Mecanismo de execução
Agendamento: O backend agenda automaticamente as tarefas de manutenção. As tarefas geralmente são executadas uma vez a cada 24 horas por tabela, mas não seguem um cronograma fixo. Cargas elevadas no sistema podem causar atrasos.
Uso de recursos: As tarefas de manutenção não consomem suas cotas de throughput ou QPS e não afetam as cargas de trabalho de produção.
Isolamento de transações: As tarefas de manutenção usam isolamento de snapshots do Iceberg. Leituras e gravações simultâneas continuam sem interrupção — o mecanismo de consulta seleciona automaticamente o snapshot válido mais recente.
Consultar status do job de manutenção
Verifique o status dos jobs de compactação, gerenciamento de snapshots e limpeza de arquivos não referenciados. Cada tipo de job relata o status independentemente.
Console
Visualize o Job status para cada tipo de manutenção na aba Data Maintenance.
Faça login no console do OSS. No painel de navegação à esquerda, escolha Table Bucket List.
Clique no nome do Table Bucket desejado. Na Table List, clique no nome da tabela para abrir sua página de detalhes.
Clique na aba Data Maintenance.
-
Em cada seção de manutenção, visualize o Job status:
Compaction: Status de execução (Failed ou Succeeded) e carimbo de data/hora da última execução.
Snapshot management: Status de execução e carimbo de data/hora da última execução do job de limpeza de snapshots.
Unreferenced file cleanup: Configurado no nível do Table Bucket. Clique em Edit Configuration in Table Bucket para visualizar o status na página Data Maintenance do Table Bucket.
Ossutil
ossutil tables-api get-table-maintenance-job-status \
--table-bucket-arn acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket \
--namespace mynamespace \
--name mytable
SDK
Python
import argparse
import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.tables as oss_tables
parser = argparse.ArgumentParser(description="get table maintenance job status sample")
parser.add_argument('--region', help='The region where the table bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS Tables.')
parser.add_argument('--table-bucket-arn', help='The ARN of the table bucket.', required=True)
parser.add_argument('--namespace', help='The namespace of the table.', required=True)
parser.add_argument('--name', help='The name of the table.', required=True)
def main():
args = parser.parse_args()
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
client = oss_tables.Client(cfg)
result = client.get_table_maintenance_job_status(
oss_tables.models.GetTableMaintenanceJobStatusRequest(
table_bucket_arn=args.table_bucket_arn,
namespace=args.namespace,
name=args.name,
)
)
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' table arn: {result.table_arn},'
f' status: {result.status}')
if __name__ == "__main__":
main()
Go
package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/tables"
)
var (
region string
tableBucketArn string
namespace string
name string
)
func init() {
flag.StringVar(®ion, "region", "", "The region where the table bucket is located.")
flag.StringVar(&tableBucketArn, "table-bucket-arn", "", "The ARN of the table bucket.")
flag.StringVar(&namespace, "namespace", "", "The namespace of the table.")
flag.StringVar(&name, "name", "", "The name of the table.")
}
func main() {
flag.Parse()
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(tableBucketArn) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table bucket arn required")
}
if len(namespace) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, namespace name required")
}
if len(name) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, table name required")
}
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
client := tables.NewTablesClient(cfg)
result, err := client.GetTableMaintenanceJobStatus(context.TODO(), &tables.GetTableMaintenanceJobStatusRequest{
TableBucketARN: oss.Ptr(tableBucketArn),
Namespace: oss.Ptr(namespace),
Name: oss.Ptr(name),
})
if err != nil {
log.Fatalf("failed to get table maintenance job status %v", err)
}
log.Printf("get table maintenance job status result:%#v\n", result)
}
Java
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.tables.OSSTablesClient;
import com.aliyun.sdk.service.oss2.tables.models.*;
public class GetTableMaintenanceJobStatusSample {
public static void main(String[] args) throws Exception {
String region = "cn-hangzhou";
String tableBucketARN = "acs:osstables:cn-hangzhou:1234567890:bucket/mytable-bucket";
String namespace = "mynamespace";
String name = "mytable";
try (OSSTablesClient client = OSSTablesClient.newBuilder()
.credentialsProvider(new EnvironmentVariableCredentialsProvider())
.region(region)
.build()) {
GetTableMaintenanceJobStatusRequest request = GetTableMaintenanceJobStatusRequest.newBuilder()
.tableBucketARN(tableBucketARN)
.namespace(namespace)
.name(name)
.build();
GetTableMaintenanceJobStatusResult result = client.getTableMaintenanceJobStatus(request);
System.out.printf("Status code:%d, request id:%s%n",
result.statusCode(), result.requestId());
System.out.printf("Table ARN: %s%n", result.tableARN());
if (result.jobStatus() != null && !result.jobStatus().isEmpty()) {
System.out.println("Maintenance job status:");
result.jobStatus().forEach((type, status) -> {
System.out.printf(" Type: %s, Status: %s%n", type, status.status());
if (status.lastRunTimestamp() != null) {
System.out.printf(" LastRunTimestamp: %s%n", status.lastRunTimestamp());
}
if (status.failureMessage() != null && !status.failureMessage().isEmpty()) {
System.out.printf(" FailureMessage: %s%n", status.failureMessage());
}
});
} else {
System.out.println("No maintenance job status found.");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
API
Chame GetTableMaintenanceJobStatus para consultar o status do job de manutenção.