Amazon Glacier: Resume a Multipart Upload
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.
Verifies the local file against its checkpoint, reads every List Parts page, and compares each exact range and tree hash. Matching parts are skipped; missing or mismatched parts are uploaded. Unexpected server ranges prevent completion. Keep the upload exclusive to this process. A missing upload may be completed, aborted, or expired: do not automatically start over. For an uncertain completion use retry completion.
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 C# Downloads
// Assumes Chilkat is unlocked. See Global Unlock Sample.
bool success = false;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/glacier.json");
if (success != true) {
Debug.WriteLine("Could not load private AWS credentials.");
return;
}
if ((credentials.JsonTypeOf("access_key") != 1) || (credentials.StringOf("access_key") == "")) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
if ((credentials.JsonTypeOf("secret_key") != 1) || (credentials.StringOf("secret_key") == "")) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
// Set this once to the region containing the vault.
string region = "us-west-2";
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("glacier.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
Chilkat.AuthAws aws = new Chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "glacier";
aws.SignatureVersion = 4;
Chilkat.Rest rest = new Chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("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") == true) {
if (credentials.JsonTypeOf("session_token") != 1) {
Debug.WriteLine("session_token must be a string.");
return;
}
if (credentials.StringOf("session_token") != "") {
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"));
if (success != true) {
Debug.WriteLine("Could not set the session-token parameter.");
return;
}
}
}
// Supply a Socket to explicitly enable TLS certificate verification.
Chilkat.Socket connection = new Chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success != true) {
Debug.WriteLine("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success != true) {
Debug.WriteLine("Could not attach the TLS connection.");
return;
}
success = rest.AddHeader("x-amz-glacier-version","2012-06-01");
if (success != true) {
Debug.WriteLine("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}","chilkat");
if (success != true) {
Debug.WriteLine("Could not set vault name.");
return;
}
Chilkat.JsonObject body = new Chilkat.JsonObject();
Chilkat.JsonObject result = new Chilkat.JsonObject();
result.Strict = true;
Chilkat.JsonObject error = new Chilkat.JsonObject();
error.Strict = true;
Chilkat.StringBuilder requestBody = new Chilkat.StringBuilder();
Chilkat.StringBuilder responseBody = new Chilkat.StringBuilder();
Chilkat.FileAccess files = new Chilkat.FileAccess();
string statePath = "qa_output/glacier-multipart.json";
string receiptPath = "qa_output/glacier-multipart-completed.json";
Chilkat.JsonObject state = new Chilkat.JsonObject();
state.Strict = true;
Chilkat.StringBuilder saved = new Chilkat.StringBuilder();
success = state.LoadFile(statePath);
if (success != true) {
Debug.WriteLine("Could not load the private multipart checkpoint.");
return;
}
if (state.JsonTypeOf("UploadId") != 1) {
Debug.WriteLine("Missing or invalid UploadId.");
return;
}
if (state.StringOf("UploadId") == "") {
Debug.WriteLine("Empty UploadId.");
return;
}
if (state.JsonTypeOf("Region") != 1) {
Debug.WriteLine("Missing or invalid Region.");
return;
}
if (state.StringOf("Region") == "") {
Debug.WriteLine("Empty Region.");
return;
}
if (state.JsonTypeOf("VaultName") != 1) {
Debug.WriteLine("Missing or invalid VaultName.");
return;
}
if (state.StringOf("VaultName") == "") {
Debug.WriteLine("Empty VaultName.");
return;
}
if (state.JsonTypeOf("FilePath") != 1) {
Debug.WriteLine("Missing or invalid FilePath.");
return;
}
if (state.StringOf("FilePath") == "") {
Debug.WriteLine("Empty FilePath.");
return;
}
if (state.JsonTypeOf("ArchiveSize") != 1) {
Debug.WriteLine("Missing or invalid ArchiveSize.");
return;
}
if (state.StringOf("ArchiveSize") == "") {
Debug.WriteLine("Empty ArchiveSize.");
return;
}
if (state.JsonTypeOf("TreeHash") != 1) {
Debug.WriteLine("Missing or invalid TreeHash.");
return;
}
if (state.StringOf("TreeHash") == "") {
Debug.WriteLine("Empty TreeHash.");
return;
}
if (state.JsonTypeOf("PartSize") != 1) {
Debug.WriteLine("Missing or invalid PartSize.");
return;
}
if (state.StringOf("PartSize") == "") {
Debug.WriteLine("Empty PartSize.");
return;
}
if ((state.StringOf("Region") != region) || (state.StringOf("VaultName") != "chilkat")) {
Debug.WriteLine("Checkpoint region/vault differs from this example configuration.");
return;
}
if (state.StringOf("PartSize") != "8388608") {
Debug.WriteLine("This workflow requires the original 8 MiB part size.");
return;
}
string uploadId = state.StringOf("UploadId");
success = rest.AddPathParam("{upload}",uploadId);
if (success != true) {
Debug.WriteLine("Could not set upload ID.");
return;
}
if (files.FileExists(receiptPath) == true) {
Debug.WriteLine("A completion receipt already exists; this upload has finished.");
return;
}
string filePath = state.StringOf("FilePath");
string fileSize = files.FileSizeStr(filePath);
if ((files.LastMethodSuccess != true) || (fileSize != state.StringOf("ArchiveSize"))) {
Debug.WriteLine("Local file size differs from the checkpoint.");
return;
}
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
crypt.HashAlgorithm = "sha256-tree-hash";
crypt.EncodingMode = "hexlower";
string treeHash = crypt.HashFileENC(filePath);
if ((crypt.LastMethodSuccess != true) || (treeHash != state.StringOf("TreeHash"))) {
Debug.WriteLine("Local file checksum differs from the checkpoint; do not resume with a different file.");
return;
}
Chilkat.Hashtable remoteParts = new Chilkat.Hashtable();
success = rest.AddQueryParam("limit","50");
if (success != true) {
Debug.WriteLine("Could not set page limit.");
return;
}
Chilkat.Hashtable seenMarkers = new Chilkat.Hashtable();
string marker = "";
bool more = true;
int page = 0;
while ((more == true)) {
if (page == 1000) {
Debug.WriteLine("Page limit reached; listing is incomplete.");
return;
}
page = page + 1;
if (marker != "") {
success = rest.AddQueryParam("marker",marker);
if (success != true) {
Debug.WriteLine("Could not set marker.");
return;
}
}
success = rest.FullRequestNoBodySb("GET","/-/vaults/{vault}/multipart-uploads/{upload}",responseBody);
if (success != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately. Check state before retrying a change.");
return;
}
if (rest.ResponseStatusCode != 200) {
Debug.WriteLine("Glacier HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = error.LoadSb(responseBody);
if (success == true) {
if (error.JsonTypeOf("code") == 1) {
Debug.WriteLine("AWS error code: " + error.StringOf("code"));
}
}
Debug.WriteLine("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"));
// Inspect full errors privately. An HTTP error is not a successful operation.
return;
}
success = result.LoadSb(responseBody);
if (success != true) {
Debug.WriteLine("Expected valid JSON response.");
return;
}
if (result.JsonTypeOf("MultipartUploadId") != 1) {
Debug.WriteLine("Missing or invalid MultipartUploadId.");
return;
}
if (result.StringOf("MultipartUploadId") == "") {
Debug.WriteLine("Empty MultipartUploadId.");
return;
}
if (result.JsonTypeOf("PartSizeInBytes") != 2) {
Debug.WriteLine("Missing or invalid PartSizeInBytes.");
return;
}
if ((result.StringOf("MultipartUploadId") != uploadId) || (result.StringOf("PartSizeInBytes") != state.StringOf("PartSize"))) {
Debug.WriteLine("Server upload identity or part size differs from checkpoint.");
return;
}
if (result.JsonTypeOf("Parts") != 4) {
Debug.WriteLine("Missing or invalid Parts.");
return;
}
int i = 0;
while ((i < result.SizeOfArray("Parts"))) {
result.I = i;
if (result.JsonTypeOf("Parts[i].RangeInBytes") != 1) {
Debug.WriteLine("Missing or invalid Parts[i].RangeInBytes.");
return;
}
if (result.StringOf("Parts[i].RangeInBytes") == "") {
Debug.WriteLine("Empty Parts[i].RangeInBytes.");
return;
}
if (result.JsonTypeOf("Parts[i].SHA256TreeHash") != 1) {
Debug.WriteLine("Missing or invalid Parts[i].SHA256TreeHash.");
return;
}
if (result.StringOf("Parts[i].SHA256TreeHash") == "") {
Debug.WriteLine("Empty Parts[i].SHA256TreeHash.");
return;
}
string remoteRange = result.StringOf("Parts[i].RangeInBytes");
if (remoteParts.Contains(remoteRange) == true) {
Debug.WriteLine("Duplicate server range; listing is inconsistent.");
return;
}
success = remoteParts.AddStr(remoteRange,result.StringOf("Parts[i].SHA256TreeHash"));
if (success != true) {
Debug.WriteLine("Could not record server part.");
return;
}
i = i + 1;
}
more = false;
if (result.JsonTypeOf("Marker") == 1) {
marker = result.StringOf("Marker");
if (marker == "") {
Debug.WriteLine("Empty marker; listing is incomplete.");
return;
}
if (seenMarkers.Contains(marker) == true) {
Debug.WriteLine("Repeated marker; listing is incomplete.");
return;
}
success = seenMarkers.AddStr(marker,"seen");
if (success != true) {
Debug.WriteLine("Could not track pagination.");
return;
}
more = true;
}
else {
if (result.JsonTypeOf("Marker") != 6) {
Debug.WriteLine("Missing or invalid Marker; listing is incomplete.");
return;
}
}
}
success = rest.RemoveQueryParam("limit");
if (success != true) {
Debug.WriteLine("Could not clear limit.");
return;
}
if (marker != "") {
success = rest.RemoveQueryParam("marker");
if (success != true) {
Debug.WriteLine("Could not clear marker.");
return;
}
}
success = files.OpenForRead(filePath);
if (success != true) {
Debug.WriteLine("Could not open the immutable source file.");
files.FileClose();
return;
}
int partSize = 8388608;
int numParts = files.GetNumBlocks(partSize);
if ((numParts < 1) || (numParts > 10000)) {
Debug.WriteLine("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;
Chilkat.StringBuilder range = new Chilkat.StringBuilder();
Chilkat.StringBuilder digits = new Chilkat.StringBuilder();
Chilkat.BinData part = new Chilkat.BinData();
int partIndex = 0;
int matchedRemoteParts = 0;
while ((partIndex < numParts)) {
success = part.Clear();
if (success != true) {
Debug.WriteLine("Could not clear part buffer.");
files.FileClose();
return;
}
success = files.ReadBlockBd(partIndex,partSize,part);
if (success != true) {
Debug.WriteLine("Could not read the source part.");
files.FileClose();
return;
}
if ((part.NumBytes == 0) || ((partIndex < numParts - 1) && (part.NumBytes != partSize))) {
Debug.WriteLine("Source file changed or a part was read incompletely.");
files.FileClose();
return;
}
range.Clear();
digits.Clear();
digits.AppendInt(byteLow);
if (byteHigh > 0) {
while ((digits.Length < 9)) {
digits.Prepend("0");
}
range.AppendInt(byteHigh);
}
range.Append(digits.GetAsString());
range.Append("-");
endHigh = byteHigh;
endLow = byteLow + part.NumBytes - 1;
if (endLow >= 1000000000) {
endLow = endLow - 1000000000;
endHigh = endHigh + 1;
}
digits.Clear();
digits.AppendInt(endLow);
if (endHigh > 0) {
while ((digits.Length < 9)) {
digits.Prepend("0");
}
range.AppendInt(endHigh);
}
range.Append(digits.GetAsString());
string rangeKey = range.GetAsString();
crypt.HashAlgorithm = "sha256-tree-hash";
string partHash = crypt.HashBdENC(part);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash source part.");
files.FileClose();
return;
}
bool sendPart = true;
if (remoteParts.Contains(rangeKey) == true) {
matchedRemoteParts = matchedRemoteParts + 1;
if (remoteParts.LookupStr(rangeKey) == partHash) {
sendPart = false;
Debug.WriteLine("Verified existing part: " + rangeKey);
}
}
if (sendPart == true) {
crypt.HashAlgorithm = "sha256";
string linearHash = crypt.HashBdENC(part);
if (crypt.LastMethodSuccess != true) {
Debug.WriteLine("Could not hash the part payload.");
files.FileClose();
return;
}
aws.PrecomputedSha256 = linearHash;
success = rest.SetAuthAws(aws);
if (success != true) {
Debug.WriteLine("Could not configure part signing.");
files.FileClose();
return;
}
success = rest.AddHeader("x-amz-content-sha256",linearHash);
if (success != true) {
Debug.WriteLine("Could not set x-amz-content-sha256.");
files.FileClose();
return;
}
success = rest.AddHeader("x-amz-sha256-tree-hash",partHash);
if (success != true) {
Debug.WriteLine("Could not set x-amz-sha256-tree-hash.");
files.FileClose();
return;
}
range.Prepend("bytes ");
range.Append("/*");
success = rest.AddHeader("Content-Range",range.GetAsString());
if (success != true) {
Debug.WriteLine("Could not set Content-Range.");
files.FileClose();
return;
}
success = rest.AddHeader("Content-Type","application/octet-stream");
if (success != true) {
Debug.WriteLine("Could not set Content-Type.");
files.FileClose();
return;
}
success = rest.FullRequestBd("PUT","/-/vaults/{vault}/multipart-uploads/{upload}",part,responseBody);
if (success != true) {
Debug.WriteLine("Part request did not complete. Keep the checkpoint and run the resume example.");
files.FileClose();
return;
}
if (rest.ResponseStatusCode != 204) {
Debug.WriteLine("Glacier HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = error.LoadSb(responseBody);
if (success == true) {
if (error.JsonTypeOf("code") == 1) {
Debug.WriteLine("AWS error code: " + error.StringOf("code"));
}
}
Debug.WriteLine("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"));
// Inspect full errors privately. An HTTP error is not a successful operation.
files.FileClose();
return;
}
string confirmedHash = rest.ResponseHdrByName("x-amz-sha256-tree-hash");
if (confirmedHash != partHash) {
Debug.WriteLine("Part response checksum mismatch. Keep the checkpoint and inspect List Parts.");
files.FileClose();
return;
}
Debug.WriteLine("Uploaded part: " + rangeKey);
}
byteLow = byteLow + part.NumBytes;
if (byteLow >= 1000000000) {
byteLow = byteLow - 1000000000;
byteHigh = byteHigh + 1;
}
partIndex = partIndex + 1;
}
files.FileClose();
if (matchedRemoteParts != remoteParts.Count) {
Debug.WriteLine("Server contains unexpected ranges. Do not complete; inspect the upload and source.");
files.FileClose();
return;
}
// Recheck the source before completion. Keep the file immutable throughout.
fileSize = files.FileSizeStr(filePath);
if ((files.LastMethodSuccess != true) || (fileSize != state.StringOf("ArchiveSize"))) {
Debug.WriteLine("Source size changed during upload; do not complete.");
files.FileClose();
return;
}
crypt.HashAlgorithm = "sha256-tree-hash";
treeHash = crypt.HashFileENC(filePath);
if ((crypt.LastMethodSuccess != true) || (treeHash != state.StringOf("TreeHash"))) {
Debug.WriteLine("Source checksum changed during upload; do not complete.");
files.FileClose();
return;
}
success = rest.AddHeader("x-amz-sha256-tree-hash",state.StringOf("TreeHash"));
if (success != true) {
Debug.WriteLine("Could not set x-amz-sha256-tree-hash.");
files.FileClose();
return;
}
success = rest.AddHeader("x-amz-archive-size",state.StringOf("ArchiveSize"));
if (success != true) {
Debug.WriteLine("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 != true) {
Debug.WriteLine("Could not reset signing.");
files.FileClose();
return;
}
success = rest.RemoveHeader("x-amz-content-sha256");
if (success != true) {
Debug.WriteLine("Could not clear part payload hash.");
files.FileClose();
return;
}
success = rest.RemoveHeader("Content-Range");
if (success != true) {
Debug.WriteLine("Could not clear part range.");
files.FileClose();
return;
}
success = rest.RemoveHeader("Content-Type");
if (success != true) {
Debug.WriteLine("Could not clear content type.");
files.FileClose();
return;
}
success = rest.FullRequestNoBodySb("POST","/-/vaults/{vault}/multipart-uploads/{upload}",responseBody);
if (success != true) {
Debug.WriteLine("Request did not complete; inspect diagnostics privately. Check state before retrying a change.");
files.FileClose();
return;
}
if (rest.ResponseStatusCode != 201) {
Debug.WriteLine("Glacier HTTP status: " + Convert.ToString(rest.ResponseStatusCode));
success = error.LoadSb(responseBody);
if (success == true) {
if (error.JsonTypeOf("code") == 1) {
Debug.WriteLine("AWS error code: " + error.StringOf("code"));
}
}
Debug.WriteLine("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"));
// Inspect full errors privately. An HTTP error is not a successful operation.
files.FileClose();
return;
}
string archiveId = rest.ResponseHdrByName("x-amz-archive-id");
if ((rest.LastMethodSuccess != true) || (archiveId == "")) {
Debug.WriteLine("Completion response has no archive ID. Preserve the checkpoint and retry identical completion promptly.");
files.FileClose();
return;
}
Debug.WriteLine("Archive ID: " + archiveId);
string location = rest.ResponseHdrByName("Location");
Debug.WriteLine("Location: " + location);
string returnedHash = rest.ResponseHdrByName("x-amz-sha256-tree-hash");
if ((rest.LastMethodSuccess == true) && (returnedHash != state.StringOf("TreeHash"))) {
Debug.WriteLine("Completion checksum mismatch; preserve the printed archive ID and investigate.");
files.FileClose();
return;
}
Chilkat.JsonObject receipt = new Chilkat.JsonObject();
success = receipt.UpdateString("UploadId",uploadId);
if (success != true) {
Debug.WriteLine("Could not set UploadId.");
files.FileClose();
return;
}
success = receipt.UpdateString("ArchiveId",archiveId);
if (success != true) {
Debug.WriteLine("Could not set ArchiveId.");
files.FileClose();
return;
}
success = receipt.UpdateString("Location",location);
if (success != true) {
Debug.WriteLine("Could not set Location.");
files.FileClose();
return;
}
success = receipt.UpdateString("TreeHash",state.StringOf("TreeHash"));
if (success != true) {
Debug.WriteLine("Could not set TreeHash.");
files.FileClose();
return;
}
saved.Clear();
success = receipt.EmitSb(saved);
if (success != true) {
Debug.WriteLine("Could not serialize receipt; preserve the printed archive ID.");
files.FileClose();
return;
}
success = saved.WriteFile(receiptPath,"utf-8",false);
if (success != true) {
Debug.WriteLine("Could not save receipt; preserve the printed archive ID.");
files.FileClose();
return;
}
Debug.WriteLine("Completion receipt saved. Keep it in your archive catalog.");