Amazon Glacier: Upload an Archive in Parts
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.
Initiates the upload, saves its ID before sending data, uploads each range with both checksums, and completes with the tree hash of the entire file. Part hashes are not concatenated as hexadecimal strings. Link: resume an interrupted upload.
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>
#import <CkoCrypt2.h>
#import <CkoBinData.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";
NSString *tempPath = @"qa_output/glacier-multipart.json.tmp";
CkoJsonObject *state = [[CkoJsonObject alloc] init];
state.Strict = YES;
CkoStringBuilder *saved = [[CkoStringBuilder alloc] init];
if (([files FileExists: statePath] == YES) || ([files FileExists: tempPath] == YES) || ([files FileExists: receiptPath] == YES)) {
NSLog(@"%@",@"Existing checkpoint/receipt found. Resume or inspect it; choose new paths for a new archive.");
return;
}
NSString *filePath = @"qa_data/zips/somethingBig.zip";
NSString *fileSize = [files FileSizeStr: filePath];
if ((files.LastMethodSuccess != YES) || (fileSize == @"0")) {
NSLog(@"%@",@"Source file must exist and be nonempty.");
return;
}
success = [files OpenForRead: filePath];
if (success != YES) {
NSLog(@"%@",@"Could not open source.");
return;
}
int initialParts = [[files GetNumBlocks: [NSNumber numberWithInt: 8388608]] intValue];
[files FileClose];
if ((initialParts < 1) || (initialParts > 10000)) {
NSLog(@"%@",@"Source exceeds the 10,000-part limit for this 8 MiB example.");
return;
}
CkoCrypt2 *crypt = [[CkoCrypt2 alloc] init];
crypt.HashAlgorithm = @"sha256-tree-hash";
crypt.EncodingMode = @"hexlower";
NSString *treeHash = [crypt HashFileENC: filePath];
if (crypt.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not hash source file.");
return;
}
success = [state UpdateString: @"Region" value: region];
if (success != YES) {
NSLog(@"%@",@"Could not set Region.");
return;
}
success = [state UpdateString: @"VaultName" value: @"chilkat"];
if (success != YES) {
NSLog(@"%@",@"Could not set VaultName.");
return;
}
success = [state UpdateString: @"FilePath" value: filePath];
if (success != YES) {
NSLog(@"%@",@"Could not set FilePath.");
return;
}
success = [state UpdateString: @"ArchiveSize" value: fileSize];
if (success != YES) {
NSLog(@"%@",@"Could not set ArchiveSize.");
return;
}
success = [state UpdateString: @"TreeHash" value: treeHash];
if (success != YES) {
NSLog(@"%@",@"Could not set TreeHash.");
return;
}
success = [state UpdateString: @"PartSize" value: @"8388608"];
if (success != YES) {
NSLog(@"%@",@"Could not set PartSize.");
return;
}
[saved Clear];
success = [state EmitSb: saved];
if (success != YES) {
NSLog(@"%@",@"Could not serialize pending checkpoint.");
return;
}
success = [saved WriteFile: tempPath charset: @"utf-8" emitBom: NO];
if (success != YES) {
NSLog(@"%@",@"Cannot write checkpoint; no upload was initiated.");
return;
}
success = [rest AddHeader: @"x-amz-part-size" value: @"8388608"];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-part-size.");
return;
}
success = [rest AddHeader: @"x-amz-archive-description" value: @"Multipart archive example"];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-archive-description.");
return;
}
success = [rest FullRequestNoBodySb: @"POST" uriPath: @"/-/vaults/{vault}/multipart-uploads" 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 *uploadId = [rest ResponseHdrByName: @"x-amz-multipart-upload-id"];
if ((rest.LastMethodSuccess != YES) || (uploadId == @"")) {
NSLog(@"%@",@"Missing upload ID. Inspect multipart uploads before initiating another upload.");
return;
}
NSLog(@"%@%@",@"Upload ID (preserve this): ",uploadId);
success = [state UpdateString: @"UploadId" value: uploadId];
if (success != YES) {
NSLog(@"%@",@"Could not set UploadId.");
return;
}
[saved Clear];
success = [state EmitSb: saved];
if (success != YES) {
NSLog(@"%@",@"Could not serialize checkpoint; preserve the printed upload ID.");
return;
}
success = [saved WriteFile: tempPath charset: @"utf-8" emitBom: NO];
if (success != YES) {
NSLog(@"%@",@"Could not persist upload ID; preserve it and stop.");
return;
}
success = [files FileRename: tempPath newPath: statePath];
if (success != YES) {
NSLog(@"%@",@"Checkpoint remains in .tmp; recover it before resuming.");
return;
}
success = [rest AddPathParam: @"{upload}" value: uploadId];
if (success != YES) {
NSLog(@"%@",@"Could not set upload ID.");
return;
}
success = [rest RemoveHeader: @"x-amz-part-size"];
if (success != YES) {
NSLog(@"%@",@"Could not clear initiation header.");
return;
}
success = [rest RemoveHeader: @"x-amz-archive-description"];
if (success != YES) {
NSLog(@"%@",@"Could not clear description header.");
return;
}
success = [files OpenForRead: filePath];
if (success != YES) {
NSLog(@"%@",@"Could not open the immutable source file.");
[files FileClose];
return;
}
int partSize = 8388608;
int numParts = [[files GetNumBlocks: [NSNumber numberWithInt: partSize]] intValue];
if ((numParts < 1) || (numParts > 10000)) {
NSLog(@"%@",@"This 8 MiB example supports nonempty files of at most 10,000 parts.");
[files FileClose];
return;
}
// Two base-1,000,000,000 components avoid 32-bit overflow in COM languages.
int byteHigh = 0;
int byteLow = 0;
int endHigh;
int endLow;
CkoStringBuilder *range = [[CkoStringBuilder alloc] init];
CkoStringBuilder *digits = [[CkoStringBuilder alloc] init];
CkoBinData *part = [[CkoBinData alloc] init];
int partIndex = 0;
while ((partIndex < numParts)) {
success = [part Clear];
if (success != YES) {
NSLog(@"%@",@"Could not clear part buffer.");
[files FileClose];
return;
}
success = [files ReadBlockBd: [NSNumber numberWithInt: partIndex] blockSize: [NSNumber numberWithInt: partSize] bd: part];
if (success != YES) {
NSLog(@"%@",@"Could not read the source part.");
[files FileClose];
return;
}
if (([part.NumBytes intValue] == 0) || ((partIndex < numParts - 1) && ([part.NumBytes intValue] != partSize))) {
NSLog(@"%@",@"Source file changed or a part was read incompletely.");
[files FileClose];
return;
}
[range Clear];
[digits Clear];
[digits AppendInt: [NSNumber numberWithInt: byteLow]];
if (byteHigh > 0) {
while (([digits.Length intValue] < 9)) {
[digits Prepend: @"0"];
}
[range AppendInt: [NSNumber numberWithInt: byteHigh]];
}
[range Append: [digits GetAsString]];
[range Append: @"-"];
endHigh = byteHigh;
endLow = byteLow + [part.NumBytes intValue] - 1;
if (endLow >= 1000000000) {
endLow = endLow - 1000000000;
endHigh = endHigh + 1;
}
[digits Clear];
[digits AppendInt: [NSNumber numberWithInt: endLow]];
if (endHigh > 0) {
while (([digits.Length intValue] < 9)) {
[digits Prepend: @"0"];
}
[range AppendInt: [NSNumber numberWithInt: endHigh]];
}
[range Append: [digits GetAsString]];
NSString *rangeKey = [range GetAsString];
crypt.HashAlgorithm = @"sha256-tree-hash";
NSString *partHash = [crypt HashBdENC: part];
if (crypt.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not hash source part.");
[files FileClose];
return;
}
BOOL sendPart = YES;
if (sendPart == YES) {
crypt.HashAlgorithm = @"sha256";
NSString *linearHash = [crypt HashBdENC: part];
if (crypt.LastMethodSuccess != YES) {
NSLog(@"%@",@"Could not hash the part payload.");
[files FileClose];
return;
}
aws.PrecomputedSha256 = linearHash;
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"Could not configure part signing.");
[files FileClose];
return;
}
success = [rest AddHeader: @"x-amz-content-sha256" value: linearHash];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-content-sha256.");
[files FileClose];
return;
}
success = [rest AddHeader: @"x-amz-sha256-tree-hash" value: partHash];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-sha256-tree-hash.");
[files FileClose];
return;
}
[range Prepend: @"bytes "];
[range Append: @"/*"];
success = [rest AddHeader: @"Content-Range" value: [range GetAsString]];
if (success != YES) {
NSLog(@"%@",@"Could not set Content-Range.");
[files FileClose];
return;
}
success = [rest AddHeader: @"Content-Type" value: @"application/octet-stream"];
if (success != YES) {
NSLog(@"%@",@"Could not set Content-Type.");
[files FileClose];
return;
}
success = [rest FullRequestBd: @"PUT" uriPath: @"/-/vaults/{vault}/multipart-uploads/{upload}" binData: part responseBody: responseBody];
if (success != YES) {
NSLog(@"%@",@"Part request did not complete. Keep the checkpoint and run the resume example.");
[files FileClose];
return;
}
if ([rest.ResponseStatusCode intValue] != 204) {
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.
[files FileClose];
return;
}
NSString *confirmedHash = [rest ResponseHdrByName: @"x-amz-sha256-tree-hash"];
if (confirmedHash != partHash) {
NSLog(@"%@",@"Part response checksum mismatch. Keep the checkpoint and inspect List Parts.");
[files FileClose];
return;
}
NSLog(@"%@%@",@"Uploaded part: ",rangeKey);
}
byteLow = byteLow + [part.NumBytes intValue];
if (byteLow >= 1000000000) {
byteLow = byteLow - 1000000000;
byteHigh = byteHigh + 1;
}
partIndex = partIndex + 1;
}
[files FileClose];
// Recheck the source before completion. Keep the file immutable throughout.
fileSize = [files FileSizeStr: filePath];
if ((files.LastMethodSuccess != YES) || (fileSize != [state StringOf: @"ArchiveSize"])) {
NSLog(@"%@",@"Source size changed during upload; do not complete.");
[files FileClose];
return;
}
crypt.HashAlgorithm = @"sha256-tree-hash";
treeHash = [crypt HashFileENC: filePath];
if ((crypt.LastMethodSuccess != YES) || (treeHash != [state StringOf: @"TreeHash"])) {
NSLog(@"%@",@"Source checksum changed during upload; do not complete.");
[files FileClose];
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.");
[files FileClose];
return;
}
success = [rest AddHeader: @"x-amz-archive-size" value: [state StringOf: @"ArchiveSize"]];
if (success != YES) {
NSLog(@"%@",@"Could not set x-amz-archive-size.");
[files FileClose];
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.");
[files FileClose];
return;
}
success = [rest RemoveHeader: @"x-amz-content-sha256"];
if (success != YES) {
NSLog(@"%@",@"Could not clear part payload hash.");
[files FileClose];
return;
}
success = [rest RemoveHeader: @"Content-Range"];
if (success != YES) {
NSLog(@"%@",@"Could not clear part range.");
[files FileClose];
return;
}
success = [rest RemoveHeader: @"Content-Type"];
if (success != YES) {
NSLog(@"%@",@"Could not clear content type.");
[files FileClose];
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.");
[files FileClose];
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.
[files FileClose];
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.");
[files FileClose];
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.");
[files FileClose];
return;
}
CkoJsonObject *receipt = [[CkoJsonObject alloc] init];
success = [receipt UpdateString: @"UploadId" value: uploadId];
if (success != YES) {
NSLog(@"%@",@"Could not set UploadId.");
[files FileClose];
return;
}
success = [receipt UpdateString: @"ArchiveId" value: archiveId];
if (success != YES) {
NSLog(@"%@",@"Could not set ArchiveId.");
[files FileClose];
return;
}
success = [receipt UpdateString: @"Location" value: location];
if (success != YES) {
NSLog(@"%@",@"Could not set Location.");
[files FileClose];
return;
}
success = [receipt UpdateString: @"TreeHash" value: [state StringOf: @"TreeHash"]];
if (success != YES) {
NSLog(@"%@",@"Could not set TreeHash.");
[files FileClose];
return;
}
[saved Clear];
success = [receipt EmitSb: saved];
if (success != YES) {
NSLog(@"%@",@"Could not serialize receipt; preserve the printed archive ID.");
[files FileClose];
return;
}
success = [saved WriteFile: receiptPath charset: @"utf-8" emitBom: NO];
if (success != YES) {
NSLog(@"%@",@"Could not save receipt; preserve the printed archive ID.");
[files FileClose];
return;
}
NSLog(@"%@",@"Completion receipt saved. Keep it in your archive catalog.");