Amazon Glacier: Download and Verify Range Retrieval Output
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.
Downloads the 8 MiB output of the companion range retrieval job. Set its job ID and create qa_output first. DescribeJob must report successful archive retrieval and the expected archive range. The HTTP range bytes=0-8388607 is relative to the job output, although the original archive range starts at 8388608.
Requires HTTP 206, exact Content-Range and Content-Length, the response tree hash, the actual downloaded size, and the job output's SHA256TreeHash before renaming the temporary file. ArchiveSHA256TreeHash hashes the entire original archive and must not be used to validate a partial retrieval. Existing output files are not overwritten. A failed download remains marked .part.
Requires glacier:DescribeJob and glacier:GetJobOutput. Download promptly: job output remains available for at least 24 hours after completion. Both retrieval and download ranges must be tree-hash aligned to receive a checksum. For other range lengths, adjust all expected ranges and lengths together.
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 Delphi DLL Downloads
var
success: Boolean;
credentials: HCkJsonObject;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
connection: HCkSocket;
result: HCkJsonObject;
error: HCkJsonObject;
responseBody: HCkStringBuilder;
jobId: PWideChar;
expectedHash: PWideChar;
rangeHeader: HCkStringBuilder;
contentRange: HCkStringBuilder;
byteCount: HCkStringBuilder;
files: HCkFileAccess;
crypt: HCkCrypt2;
temporaryPath: PWideChar;
finalPath: PWideChar;
httpStatus: Integer;
responseRange: PWideChar;
responseLength: PWideChar;
responseHash: PWideChar;
output: HCkStream;
actualSize: PWideChar;
actualHash: PWideChar;
begin
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the Glacier operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/glacier.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load private AWS credentials.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (CkJsonObject__stringOf(credentials,'access_key') = '')) then
begin
Memo1.Lines.Add('Missing or invalid access_key.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (CkJsonObject__stringOf(credentials,'secret_key') = '')) then
begin
Memo1.Lines.Add('Missing or invalid secret_key.');
Exit;
end;
// Set this once to the region containing the vault.
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'glacier.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'glacier');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
begin
Memo1.Lines.Add('Could not configure AWS signing.');
Exit;
end;
// 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 (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
begin
Memo1.Lines.Add('session_token must be a string.');
Exit;
end;
if (CkJsonObject__stringOf(credentials,'session_token') <> '') then
begin
success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set the session-token parameter.');
Exit;
end;
end;
end;
// Supply a Socket to explicitly enable TLS certificate verification.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
begin
Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
Exit;
end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
begin
Memo1.Lines.Add('Could not attach the TLS connection.');
Exit;
end;
success := CkRest_AddHeader(rest,'x-amz-glacier-version','2012-06-01');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set x-amz-glacier-version.');
Exit;
end;
// A hyphen selects the account belonging to the signing credentials.
// Use the original, URL-safe vault name and IDs returned by Glacier.
success := CkRest_AddPathParam(rest,'{vault}','chilkat');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set vault name.');
Exit;
end;
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
error := CkJsonObject_Create();
CkJsonObject_putStrict(error,True);
responseBody := CkStringBuilder_Create();
jobId := 'YOUR_JOB_ID';
success := CkRest_AddPathParam(rest,'{job}',jobId);
if (success <> True) then
begin
Memo1.Lines.Add('Could not set job ID.');
Exit;
end;
success := CkRest_FullRequestNoBodySb(rest,'GET','/-/vaults/{vault}/jobs/{job}',responseBody);
if (success <> True) then
begin
Memo1.Lines.Add('Request did not complete; inspect diagnostics privately. Check state before retrying a change.');
Exit;
end;
if (CkRest_getResponseStatusCode(rest) <> 200) then
begin
Memo1.Lines.Add('Glacier HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
success := CkJsonObject_LoadSb(error,responseBody);
if (success = True) then
begin
if (CkJsonObject_JsonTypeOf(error,'code') = 1) then
begin
Memo1.Lines.Add('AWS error code: ' + CkJsonObject__stringOf(error,'code'));
end;
end;
Memo1.Lines.Add('AWS request ID: ' + CkRest__responseHdrByName(rest,'x-amzn-RequestId'));
// Inspect full errors privately. An HTTP error is not a successful operation.
Exit;
end;
success := CkJsonObject_LoadSb(result,responseBody);
if (success <> True) then
begin
Memo1.Lines.Add('Expected valid JSON response.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'Completed') <> 5) then
begin
Memo1.Lines.Add('Missing or invalid Completed.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'StatusCode') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid StatusCode.');
Exit;
end;
if (CkJsonObject__stringOf(result,'StatusCode') = '') then
begin
Memo1.Lines.Add('Empty StatusCode.');
Exit;
end;
if ((CkJsonObject_BoolOf(result,'Completed') <> True) or (CkJsonObject__stringOf(result,'StatusCode') <> 'Succeeded')) then
begin
Memo1.Lines.Add('Job is not successfully complete. Resume later only if InProgress.');
Exit;
end;
if (CkJsonObject__stringOf(result,'Action') <> 'ArchiveRetrieval') then
begin
Memo1.Lines.Add('Wrong job type.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(result,'SHA256TreeHash') <> 1) then
begin
Memo1.Lines.Add('Missing or invalid SHA256TreeHash.');
Exit;
end;
if (CkJsonObject__stringOf(result,'SHA256TreeHash') = '') then
begin
Memo1.Lines.Add('Empty SHA256TreeHash.');
Exit;
end;
if (CkJsonObject__stringOf(result,'RetrievalByteRange') <> '8388608-16777215') then
begin
Memo1.Lines.Add('Use the 8 MiB range job created by the companion example.');
Exit;
end;
// These offsets are relative to the JOB OUTPUT, not the original archive.
// Output bytes 0..8388607 correspond to archive bytes 8388608..16777215.
expectedHash := CkJsonObject__stringOf(result,'SHA256TreeHash');
rangeHeader := CkStringBuilder_Create();
contentRange := CkStringBuilder_Create();
byteCount := CkStringBuilder_Create();
CkStringBuilder_Append(rangeHeader,'bytes=0-8388607');
CkStringBuilder_Append(contentRange,'bytes 0-8388607/8388608');
CkStringBuilder_Append(byteCount,'8388608');
files := CkFileAccess_Create();
crypt := CkCrypt2_Create();
CkCrypt2_putHashAlgorithm(crypt,'sha256-tree-hash');
CkCrypt2_putEncodingMode(crypt,'hexlower');
temporaryPath := 'qa_output/archive-range.dat.part';
finalPath := 'qa_output/archive-range.dat';
if ((CkFileAccess_FileExists(files,temporaryPath) = True) or (CkFileAccess_FileExists(files,finalPath) = True)) then
begin
Memo1.Lines.Add('Choose unused output paths.');
Exit;
end;
success := CkRest_AddHeader(rest,'Range',CkStringBuilder__getAsString(rangeHeader));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set Range.');
Exit;
end;
success := CkRest_SendReqNoBody(rest,'GET','/-/vaults/{vault}/jobs/{job}/output');
if (success <> True) then
begin
Memo1.Lines.Add('Could not send range request. Rerun to resume.');
Exit;
end;
httpStatus := CkRest_ReadResponseHeader(rest);
if (httpStatus <> 206) then
begin
Memo1.Lines.Add('Expected HTTP 206 for range download. Job may have expired; no new retrieval was started.');
Exit;
end;
responseRange := CkRest__responseHdrByName(rest,'Content-Range');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseRange <> CkStringBuilder__getAsString(contentRange))) then
begin
Memo1.Lines.Add('Unexpected Content-Range; refusing download.');
Exit;
end;
responseLength := CkRest__responseHdrByName(rest,'Content-Length');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseLength <> CkStringBuilder__getAsString(byteCount))) then
begin
Memo1.Lines.Add('Unexpected Content-Length; refusing download.');
Exit;
end;
responseHash := CkRest__responseHdrByName(rest,'x-amz-sha256-tree-hash');
if ((CkRest_getLastMethodSuccess(rest) <> True) or (responseHash = '')) then
begin
Memo1.Lines.Add('Missing range tree hash. Require a tree-hash-aligned retrieval and download range.');
Exit;
end;
output := CkStream_Create();
CkStream_putSinkFile(output,temporaryPath);
success := CkRest_ReadRespBodyStream(rest,output,True);
if (success <> True) then
begin
Memo1.Lines.Add('Download interrupted; rerun to resume. Temporary bytes are not trusted.');
Exit;
end;
actualSize := CkFileAccess__fileSizeStr(files,temporaryPath);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (actualSize <> CkStringBuilder__getAsString(byteCount))) then
begin
Memo1.Lines.Add('Downloaded size mismatch.');
Exit;
end;
actualHash := CkCrypt2__hashFileENC(crypt,temporaryPath);
if ((CkCrypt2_getLastMethodSuccess(crypt) <> True) or (actualHash <> responseHash)) then
begin
Memo1.Lines.Add('Downloaded tree hash mismatch.');
Exit;
end;
if (actualHash <> expectedHash) then
begin
Memo1.Lines.Add('Range output does not match the retrieval job tree hash.');
Exit;
end;
success := CkFileAccess_FileRename(files,temporaryPath,finalPath);
if (success <> True) then
begin
Memo1.Lines.Add('Verified range remains at the temporary path; rename failed.');
Exit;
end;
Memo1.Lines.Add('Archive range downloaded and verified.');
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkJsonObject_Dispose(result);
CkJsonObject_Dispose(error);
CkStringBuilder_Dispose(responseBody);
CkStringBuilder_Dispose(rangeHeader);
CkStringBuilder_Dispose(contentRange);
CkStringBuilder_Dispose(byteCount);
CkFileAccess_Dispose(files);
CkCrypt2_Dispose(crypt);
CkStream_Dispose(output);