Use InitiateJob com um AWS SDK ou CLI - Amazon S3 Glacier

Esta página é somente para clientes existentes do serviço S3 Glacier que usam o Vaults e a API REST original de 2012.

Se você estiver procurando por soluções de armazenamento de arquivamento, sugerimos usar as classes de armazenamento S3 Glacier no Amazon S3, S3 Glacier Instant Retrieval, S3 Glacier Flexible Retrieval e S3 Glacier Deep Archive. Para saber mais sobre essas opções de armazenamento, consulte Classes de armazenamento S3 Glacier e Armazenamento de dados de longo prazo usando classes de armazenamento S3 Glacier no Guia do usuário do Amazon S3. Essas classes de armazenamento usam a API do Amazon S3, estão disponíveis em todas as regiões e podem ser gerenciadas no console do Amazon S3. Eles oferecem recursos como análise de custos de armazenamento, lente de armazenamento, recursos de segurança, incluindo várias opções de criptografia e muito mais.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use InitiateJob com um AWS SDK ou CLI

Os exemplos de códigos a seguir mostram como usar InitiateJob.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Recupere um arquivo de um cofre. Este exemplo usa a ArchiveTransferManager classe. Para obter detalhes da API, consulte ArchiveTransferManager.

/// <summary> /// Download an archive from an Amazon S3 Glacier vault using the Archive /// Transfer Manager. /// </summary> /// <param name="vaultName">The name of the vault containing the object.</param> /// <param name="archiveId">The Id of the archive to download.</param> /// <param name="localFilePath">The local directory where the file will /// be stored after download.</param> /// <returns>Async Task.</returns> public async Task<bool> DownloadArchiveWithArchiveManagerAsync(string vaultName, string archiveId, string localFilePath) { try { var manager = new ArchiveTransferManager(_glacierService); var options = new DownloadOptions { StreamTransferProgress = Progress!, }; // Download an archive. Console.WriteLine("Initiating the archive retrieval job and then polling SQS queue for the archive to be available."); Console.WriteLine("When the archive is available, downloading will begin."); await manager.DownloadAsync(vaultName, archiveId, localFilePath, options); return true; } catch (AmazonGlacierException ex) { Console.WriteLine(ex.Message); return false; } } /// <summary> /// Event handler to track the progress of the Archive Transfer Manager. /// </summary> /// <param name="sender">The object that raised the event.</param> /// <param name="args">The argument values from the object that raised the /// event.</param> static void Progress(object sender, StreamTransferProgressArgs args) { if (args.PercentDone != _currentPercentage) { _currentPercentage = args.PercentDone; Console.WriteLine($"Downloaded {_currentPercentage}%"); } }
  • Para obter detalhes da API, consulte InitiateJoba Referência AWS SDK for .NET da API.

CLI
AWS CLI

O comando a seguir inicia um trabalho para obter um inventário do cofre: my-vault

aws glacier initiate-job --account-id - --vault-name my-vault --job-parameters '{"Type": "inventory-retrieval"}'

Saída:

{ "location": "/0123456789012/vaults/my-vault/jobs/zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW", "jobId": "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW" }

O Amazon Glacier exige um argumento de ID de conta ao realizar operações, mas você pode usar um hífen para especificar a conta em uso.

O comando a seguir inicia um trabalho para recuperar um arquivo do cofre: my-vault

aws glacier initiate-job --account-id - --vault-name my-vault --job-parameters file://job-archive-retrieval.json

job-archive-retrieval.jsoné um arquivo JSON na pasta local que especifica o tipo de trabalho, o ID de arquivamento e alguns parâmetros opcionais:

{ "Type": "archive-retrieval", "ArchiveId": "kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw", "Description": "Retrieve archive on 2015-07-17", "SNSTopic": "arn:aws:sns:us-west-2:0123456789012:my-topic" }

Os IDs de arquivamento estão disponíveis na saída de aws glacier upload-archive aws glacier get-job-output e.

Saída:

{ "location": "/011685312445/vaults/mwunderl/jobs/l7IL5-EkXyEY9Ws95fClzIbk2O5uLYaFdAYOi-azsX_Z8V6NH4yERHzars8wTKYQMX6nBDI9cMNHzyZJO59-8N9aHWav", "jobId": "l7IL5-EkXy2O5uLYaFdAYOiEY9Ws95fClzIbk-azsX_Z8V6NH4yERHzars8wTKYQMX6nBDI9cMNHzyZJO59-8N9aHWav" }

Consulte Initiate Job na referência da API do Amazon Glacier para obter detalhes sobre o formato dos parâmetros do trabalho.

  • Para obter detalhes da API, consulte InitiateJobna Referência de AWS CLI Comandos.

Java
SDK para Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Recupere um inventário do cofre.

import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.glacier.GlacierClient; import software.amazon.awssdk.services.glacier.model.JobParameters; import software.amazon.awssdk.services.glacier.model.InitiateJobResponse; import software.amazon.awssdk.services.glacier.model.GlacierException; import software.amazon.awssdk.services.glacier.model.InitiateJobRequest; import software.amazon.awssdk.services.glacier.model.DescribeJobRequest; import software.amazon.awssdk.services.glacier.model.DescribeJobResponse; import software.amazon.awssdk.services.glacier.model.GetJobOutputRequest; import software.amazon.awssdk.services.glacier.model.GetJobOutputResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ArchiveDownload { public static void main(String[] args) { final String usage = """ Usage: <vaultName> <accountId> <path> Where: vaultName - The name of the vault. accountId - The account ID value. path - The path where the file is written to. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String vaultName = args[0]; String accountId = args[1]; String path = args[2]; GlacierClient glacier = GlacierClient.builder() .region(Region.US_EAST_1) .build(); String jobNum = createJob(glacier, vaultName, accountId); checkJob(glacier, jobNum, vaultName, accountId, path); glacier.close(); } public static String createJob(GlacierClient glacier, String vaultName, String accountId) { try { JobParameters job = JobParameters.builder() .type("inventory-retrieval") .build(); InitiateJobRequest initJob = InitiateJobRequest.builder() .jobParameters(job) .accountId(accountId) .vaultName(vaultName) .build(); InitiateJobResponse response = glacier.initiateJob(initJob); System.out.println("The job ID is: " + response.jobId()); System.out.println("The relative URI path of the job is: " + response.location()); return response.jobId(); } catch (GlacierException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } // Poll S3 Glacier = Polling a Job may take 4-6 hours according to the // Documentation. public static void checkJob(GlacierClient glacier, String jobId, String name, String account, String path) { try { boolean finished = false; String jobStatus; int yy = 0; while (!finished) { DescribeJobRequest jobRequest = DescribeJobRequest.builder() .jobId(jobId) .accountId(account) .vaultName(name) .build(); DescribeJobResponse response = glacier.describeJob(jobRequest); jobStatus = response.statusCodeAsString(); if (jobStatus.compareTo("Succeeded") == 0) finished = true; else { System.out.println(yy + " status is: " + jobStatus); Thread.sleep(1000); } yy++; } System.out.println("Job has Succeeded"); GetJobOutputRequest jobOutputRequest = GetJobOutputRequest.builder() .jobId(jobId) .vaultName(name) .accountId(account) .build(); ResponseBytes<GetJobOutputResponse> objectBytes = glacier.getJobOutputAsBytes(jobOutputRequest); // Write the data to a local file. byte[] data = objectBytes.asByteArray(); File myFile = new File(path); OutputStream os = new FileOutputStream(myFile); os.write(data); System.out.println("Successfully obtained bytes from a Glacier vault"); os.close(); } catch (GlacierException | InterruptedException | IOException e) { System.out.println(e.getMessage()); System.exit(1); } } }
  • Para obter detalhes da API, consulte InitiateJoba Referência AWS SDK for Java 2.x da API.

PowerShell
Ferramentas para PowerShell

Exemplo 1: inicia um trabalho para recuperar um arquivo do cofre especificado de propriedade do usuário. O status do trabalho pode ser verificado usando o cmdlet Get-GlcJob. Quando o trabalho é concluído com êxito, o JobOutput cmdlet Read-GC pode ser usado para recuperar o conteúdo do arquivamento no sistema de arquivos local.

Start-GLCJob -VaultName myvault -JobType "archive-retrieval" -JobDescription "archive retrieval" -ArchiveId "o9O9j...TX-TpIhQJw"

Saída:

JobId JobOutputPath Location ----- ------------- -------- op1x...JSbthM /012345678912/vaults/test/jobs/op1xe...I4HqCHkSJSbthM
  • Para obter detalhes da API, consulte InitiateJobem Referência de AWS Tools for PowerShell cmdlet.

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Recupere um inventário do cofre.

class GlacierWrapper: """Encapsulates Amazon S3 Glacier API operations.""" def __init__(self, glacier_resource): """ :param glacier_resource: A Boto3 Amazon S3 Glacier resource. """ self.glacier_resource = glacier_resource @staticmethod def initiate_inventory_retrieval(vault): """ Initiates an inventory retrieval job. The inventory describes the contents of the vault. Standard retrievals typically complete within 3—5 hours. When the job completes, you can get the inventory by calling get_output(). :param vault: The vault to inventory. :return: The inventory retrieval job. """ try: job = vault.initiate_inventory_retrieval() logger.info("Started %s job with ID %s.", job.action, job.id) except ClientError: logger.exception("Couldn't start job on vault %s.", vault.name) raise else: return job

Recupere um arquivo de um cofre.

class GlacierWrapper: """Encapsulates Amazon S3 Glacier API operations.""" def __init__(self, glacier_resource): """ :param glacier_resource: A Boto3 Amazon S3 Glacier resource. """ self.glacier_resource = glacier_resource @staticmethod def initiate_archive_retrieval(archive): """ Initiates an archive retrieval job. Standard retrievals typically complete within 3—5 hours. When the job completes, you can get the archive contents by calling get_output(). :param archive: The archive to retrieve. :return: The archive retrieval job. """ try: job = archive.initiate_archive_retrieval() logger.info("Started %s job with ID %s.", job.action, job.id) except ClientError: logger.exception("Couldn't start job on archive %s.", archive.id) raise else: return job
  • Para obter detalhes da API, consulte a InitiateJobReferência da API AWS SDK for Python (Boto3).

Para obter uma lista completa dos guias do desenvolvedor do AWS SDK e exemplos de código, consulteUsando o S3 Glacier com um SDK AWS. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.