Amazon Glacier: Upload Archive from a File
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.
Computes both SHA-256 hashes, uploads immutable archive bytes, checks HTTP 201 and the returned tree hash, and prints the archive ID for durable storage in your catalog. A description is optional, must be printable ASCII, and is limited to 1,024 characters; it is not a lookup key. Single-request uploads support up to 4 GiB; use multipart upload for larger archives. This variant hashes and streams a file without buffering the full upload; the file must remain unchanged.
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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
final credentials = CkJsonObject();
credentials.strict = true;
try {
credentials.loadFile('qa_data/aws/glacier.json');
} on ChilkatException {
print('Could not load private AWS credentials.');
return;
}
if ((credentials.jsonTypeOf('access_key') != 1) || (credentials.stringOf('access_key') == '')) {
print('Missing or invalid access_key.');
return;
}
if ((credentials.jsonTypeOf('secret_key') != 1) || (credentials.stringOf('secret_key') == '')) {
print('Missing or invalid secret_key.');
return;
}
// Set this once to the region containing the vault.
final region = 'us-west-2';
final endpoint = CkStringBuilder();
endpoint.append('glacier.');
endpoint.append(region);
endpoint.append('.amazonaws.com');
final aws = CkAuthAws();
aws.accessKey = credentials.stringOf('access_key');
aws.secretKey = credentials.stringOf('secret_key');
aws.region = region;
aws.serviceName = 'glacier';
aws.signatureVersion = 4;
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
try {
rest.setAuthAws(aws);
} on ChilkatException {
print('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')) {
if (credentials.jsonTypeOf('session_token') != 1) {
print('session_token must be a string.');
return;
}
if (credentials.stringOf('session_token') != '') {
try {
rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
} on ChilkatException {
print('Could not set the session-token parameter.');
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
try {
rest.useConnection(connection, true);
} on ChilkatException {
print('Could not attach the TLS connection.');
return;
}
try {
rest.addHeader('x-amz-glacier-version', '2012-06-01');
} on ChilkatException {
print('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.
try {
rest.addPathParam('{vault}', 'chilkat');
} on ChilkatException {
print('Could not set vault name.');
return;
}
final body = CkJsonObject();
final result = CkJsonObject();
result.strict = true;
final error = CkJsonObject();
error.strict = true;
final requestBody = CkStringBuilder();
final responseBody = CkStringBuilder();
final filePath = 'qa_data/zips/somethingBig.zip';
// Keep this file unchanged during BOTH hashing passes and the upload.
final crypt = CkCrypt2();
crypt.hashAlgorithm = 'sha256-tree-hash';
crypt.encodingMode = 'hexlower';
final files = CkFileAccess();
final String fileSize;
try {
fileSize = files.fileSizeStr(filePath);
} on ChilkatException {
print('Could not read archive file size.');
return;
}
if (fileSize == '0') {
crypt.hashAlgorithm = 'sha256';
}
final String treeHash;
try {
treeHash = crypt.hashFileENC(filePath);
} on ChilkatException {
print('Could not compute tree hash.');
return;
}
try {
rest.addHeader('x-amz-sha256-tree-hash', treeHash);
} on ChilkatException {
print('Could not set x-amz-sha256-tree-hash.');
return;
}
crypt.hashAlgorithm = 'sha256';
final String linearHash;
try {
linearHash = crypt.hashFileENC(filePath);
} on ChilkatException {
print('Could not compute payload hash.');
return;
}
aws.precomputedSha256 = linearHash;
// Set the precomputed hash before attaching the signing configuration again.
try {
rest.setAuthAws(aws);
} on ChilkatException {
print('Could not update AWS signing.');
return;
}
try {
rest.addHeader('x-amz-content-sha256', linearHash);
} on ChilkatException {
print('Could not set x-amz-content-sha256.');
return;
}
try {
rest.addHeader('x-amz-archive-description', 'Example archive');
} on ChilkatException {
print('Could not set x-amz-archive-description.');
return;
}
final fileStream = CkStream();
fileStream.sourceFile = filePath;
rest.streamNonChunked = true;
rest.idleTimeoutMs = 120000;
connection.maxReadIdleMs = 120000;
connection.maxSendIdleMs = 120000;
final String response;
try {
response = rest.fullRequestStream('POST', '/-/vaults/{vault}/archives', fileStream);
} on ChilkatException {
print('Upload did not complete; check for an accepted archive before retrying.');
return;
}
responseBody.append(response);
if (rest.responseStatusCode != 201) {
print('Glacier HTTP status: ${rest.responseStatusCode}');
try {
error.loadSb(responseBody);
if (error.jsonTypeOf('code') == 1) {
print('AWS error code: ${error.stringOf('code')}');
}
} on ChilkatException {
// error.loadSb() failed; continue anyway.
}
print('AWS request ID: ${rest.responseHdrByName('x-amzn-RequestId')}');
// Inspect full errors privately. An HTTP error is not a successful operation.
return;
}
final archiveId = rest.responseHdrByName('x-amz-archive-id');
if ((!rest.lastMethodSuccess) || (archiveId == '')) {
print('Missing archive ID; investigate the accepted upload before retrying.');
return;
}
// Save this ID even if subsequent checksum verification fails.
print('Archive ID: $archiveId');
print('Location: ${rest.responseHdrByName('Location')}');
final returnedHash = rest.responseHdrByName('x-amz-sha256-tree-hash');
if (returnedHash != treeHash) {
print('Upload response checksum mismatch; preserve the archive ID and investigate.');
return;
}
print('Archive upload verified. Persist its ID and checksum in your archive catalog.');
}