Amazon Glacier: Retry Multipart Completion
See more Amazon Glacier Examples
For existing Amazon Glacier vault customers. The standalone vault service is closed to new customers. These examples use its REST API version 2012-06-01, not the S3 bucket APIs used by S3 Glacier storage classes. See AWS service guidance.
Uses fixed 8 MiB parts, at most 10,000 parts (78.125 GiB), and buffers one part at a time. The API also allows other power-of-two MiB sizes up to 4 GiB; this portable example deliberately fixes the size. The last part may be smaller. Use a nonempty, immutable file and one writer per upload. Create qa_output first. Byte offsets and archive sizes stay exact in languages with 32-bit integers.
The private checkpoint stores the upload ID, region, vault, file path, size, part size, and full-file tree hash. Preserve it across failures. It contains no AWS credentials. A separate completion receipt records the archive ID. A lost initiation response requires inspecting List Multipart Uploads; starting a new upload is not a retry of the old one. Inactive uploads can expire after 24 hours. Do not abort automatically on transient errors.
Use only after all parts were uploaded and a previous completion response was lost. Sends the identical upload ID, total size, and complete tree hash from the checkpoint, without listing parts or re-uploading bytes. AWS permits idempotent completion for a short period and returns the same archive ID. After completion, List Parts and List Multipart Uploads no longer expose the upload. This example deliberately does not require the local source file. A later 404 cannot prove whether the archive was completed; preserve the checkpoint and investigate your archive catalog/inventory.
Uses AWS Signature Version 4 with service glacier. Set the region once; the example builds the commercial AWS endpoint. Other partitions require the appropriate endpoint suffix. /-/ selects the signing account; change the vault name and IDs to your own resources. Load private qa_data/aws/glacier.json with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles or refresh credentials. TLS certificate verification is enabled explicitly.
Checks transport completion, the operation-specific HTTP status, and parsed data separately. Inspect full diagnostics privately. Renew expired credentials; use bounded backoff with jitter for retryable reads. Uploads and job initiation can succeed before a connection fails, so do not blindly resubmit them. Configure IAM permissions for only the required operations and vault resources.
Chilkat Objective-C Downloads
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoFileAccess.h>
// Assumes Chilkat is unlocked. See Global Unlock Sample.
BOOL success = NO;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
CkoJsonObject *credentials = [[CkoJsonObject alloc] init];
credentials.Strict = YES;
success = [credentials LoadFile: @"qa_data/aws/glacier.json"];
if (success != YES) {
NSLog(@"%@",@"Could not load private AWS credentials.");
return;
}
if (([[credentials JsonTypeOf: @"access_key"] intValue] != 1) || ([credentials StringOf: @"access_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid access_key.");
return;
}
if (([[credentials JsonTypeOf: @"secret_key"] intValue] != 1) || ([credentials StringOf: @"secret_key"] == @"")) {
NSLog(@"%@",@"Missing or invalid secret_key.");
return;
}
// Set this once to the region containing the vault.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"glacier."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = [credentials StringOf: @"access_key"];
aws.SecretKey = [credentials StringOf: @"secret_key"];
aws.Region = region;
aws.ServiceName = @"glacier";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"Could not configure AWS signing.");
return;
}
// Temporary IAM/STS credentials require their session token on every signed request.
// Include the token in the signed query. Keep request URLs and diagnostics private.
// Leave session_token absent or empty only for credentials that do not have one.
if ([credentials HasMember: @"session_token"] == YES) {
if ([[credentials JsonTypeOf: @"session_token"] intValue] != 1) {
NSLog(@"%@",@"session_token must be a string.");
return;
}
if ([credentials StringOf: @"session_token"] != @"") {
success = [rest AddQueryParam: @"X-Amz-Security-Token" value: [credentials StringOf: @"session_token"]];
if (success != YES) {
NSLog(@"%@",@"Could not set the session-token parameter.");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
return;
}
success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
NSLog(@"%@",@"Could not attach the TLS connection.");
return;
}
success = [rest AddHeader: @"x-amz-glacier-version" value: @"2012-06-01"];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-glacier-version.");
return;
}
// A hyphen selects the account belonging to the signing credentials.
// Use the original, URL-safe vault name and IDs returned by Glacier.
success = [rest AddPathParam: @"{vault}" value: @"chilkat"];
if (success != YES) {
NSLog(@"%@",@"Could not set vault name.");
return;
}
CkoJsonObject *body = [[CkoJsonObject alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
CkoJsonObject *error = [[CkoJsonObject alloc] init];
error.Strict = YES;
CkoStringBuilder *requestBody = [[CkoStringBuilder alloc] init];
CkoStringBuilder *responseBody = [[CkoStringBuilder alloc] init];
CkoFileAccess *files = [[CkoFileAccess alloc] init];
NSString *statePath = @"qa_output/glacier-multipart.json";
NSString *receiptPath = @"qa_output/glacier-multipart-completed.json";
CkoJsonObject *state = [[CkoJsonObject alloc] init];
state.Strict = YES;
CkoStringBuilder *saved = [[CkoStringBuilder alloc] init];
success = [state LoadFile: statePath];
if (success != YES) {
NSLog(@"%@",@"Could not load the private multipart checkpoint.");
return;
}
if ([[state JsonTypeOf: @"UploadId"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid UploadId.");
return;
}
if ([state StringOf: @"UploadId"] == @"") {
NSLog(@"%@",@"Empty UploadId.");
return;
}
if ([[state JsonTypeOf: @"Region"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid Region.");
return;
}
if ([state StringOf: @"Region"] == @"") {
NSLog(@"%@",@"Empty Region.");
return;
}
if ([[state JsonTypeOf: @"VaultName"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid VaultName.");
return;
}
if ([state StringOf: @"VaultName"] == @"") {
NSLog(@"%@",@"Empty VaultName.");
return;
}
if ([[state JsonTypeOf: @"FilePath"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid FilePath.");
return;
}
if ([state StringOf: @"FilePath"] == @"") {
NSLog(@"%@",@"Empty FilePath.");
return;
}
if ([[state JsonTypeOf: @"ArchiveSize"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid ArchiveSize.");
return;
}
if ([state StringOf: @"ArchiveSize"] == @"") {
NSLog(@"%@",@"Empty ArchiveSize.");
return;
}
if ([[state JsonTypeOf: @"TreeHash"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid TreeHash.");
return;
}
if ([state StringOf: @"TreeHash"] == @"") {
NSLog(@"%@",@"Empty TreeHash.");
return;
}
if ([[state JsonTypeOf: @"PartSize"] intValue] != 1) {
NSLog(@"%@",@"Missing or invalid PartSize.");
return;
}
if ([state StringOf: @"PartSize"] == @"") {
NSLog(@"%@",@"Empty PartSize.");
return;
}
if (([state StringOf: @"Region"] != region) || ([state StringOf: @"VaultName"] != @"chilkat")) {
NSLog(@"%@",@"Checkpoint region/vault differs from this example configuration.");
return;
}
if ([state StringOf: @"PartSize"] != @"8388608") {
NSLog(@"%@",@"This workflow requires the original 8 MiB part size.");
return;
}
NSString *uploadId = [state StringOf: @"UploadId"];
success = [rest AddPathParam: @"{upload}" value: uploadId];
if (success != YES) {
NSLog(@"%@",@"Could not set upload ID.");
return;
}
if ([files FileExists: receiptPath] == YES) {
NSLog(@"%@",@"A completion receipt already exists; read its archive ID.");
return;
}
success = [rest AddHeader: @"x-amz-sha256-tree-hash" value: [state StringOf: @"TreeHash"]];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-sha256-tree-hash.");
return;
}
success = [rest AddHeader: @"x-amz-archive-size" value: [state StringOf: @"ArchiveSize"]];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-archive-size.");
return;
}
// Completion has NO body: never reuse a part's precomputed payload hash.
aws.PrecomputedSha256 = @"";
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"Could not reset signing.");
return;
}
success = [rest RemoveHeader: @"x-amz-content-sha256"];
if (success != YES) {
NSLog(@"%@",@"Could not clear part payload hash.");
return;
}
success = [rest RemoveHeader: @"Content-Range"];
if (success != YES) {
NSLog(@"%@",@"Could not clear part range.");
return;
}
success = [rest RemoveHeader: @"Content-Type"];
if (success != YES) {
NSLog(@"%@",@"Could not clear content type.");
return;
}
success = [rest FullRequestNoBodySb: @"POST" uriPath: @"/-/vaults/{vault}/multipart-uploads/{upload}" sb: responseBody];
if (success != YES) {
NSLog(@"%@",@"Request did not complete; inspect diagnostics privately. Check state before retrying a change.");
return;
}
if ([rest.ResponseStatusCode intValue] != 201) {
NSLog(@"%@%d",@"Glacier HTTP status: ",[rest.ResponseStatusCode intValue]);
success = [error LoadSb: responseBody];
if (success == YES) {
if ([[error JsonTypeOf: @"code"] intValue] == 1) {
NSLog(@"%@%@",@"AWS error code: ",[error StringOf: @"code"]);
}
}
NSLog(@"%@%@",@"AWS request ID: ",[rest ResponseHdrByName: @"x-amzn-RequestId"]);
// Inspect full errors privately. An HTTP error is not a successful operation.
return;
}
NSString *archiveId = [rest ResponseHdrByName: @"x-amz-archive-id"];
if ((rest.LastMethodSuccess != YES) || (archiveId == @"")) {
NSLog(@"%@",@"Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.");
return;
}
NSLog(@"%@%@",@"Archive ID: ",archiveId);
NSString *location = [rest ResponseHdrByName: @"Location"];
NSLog(@"%@%@",@"Location: ",location);
NSString *returnedHash = [rest ResponseHdrByName: @"x-amz-sha256-tree-hash"];
if ((rest.LastMethodSuccess == YES) && (returnedHash != [state StringOf: @"TreeHash"])) {
NSLog(@"%@",@"Completion checksum mismatch; preserve the printed archive ID and investigate.");
return;
}
CkoJsonObject *receipt = [[CkoJsonObject alloc] init];
success = [receipt UpdateString: @"UploadId" value: uploadId];
if (success != YES) {
NSLog(@"%@",@"Could not set UploadId.");
return;
}
success = [receipt UpdateString: @"ArchiveId" value: archiveId];
if (success != YES) {
NSLog(@"%@",@"Could not set ArchiveId.");
return;
}
success = [receipt UpdateString: @"Location" value: location];
if (success != YES) {
NSLog(@"%@",@"Could not set Location.");
return;
}
success = [receipt UpdateString: @"TreeHash" value: [state StringOf: @"TreeHash"]];
if (success != YES) {
NSLog(@"%@",@"Could not set TreeHash.");
return;
}
[saved Clear];
success = [receipt EmitSb: saved];
if (success != YES) {
NSLog(@"%@",@"Could not serialize receipt; preserve the printed archive ID.");
return;
}
success = [saved WriteFile: receiptPath charset: @"utf-8" emitBom: NO];
if (success != YES) {
NSLog(@"%@",@"Could not save receipt; preserve the printed archive ID.");
return;
}
NSLog(@"%@",@"Completion receipt saved. Keep it in your archive catalog.");