-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·550 lines (517 loc) · 20.2 KB
/
index.js
File metadata and controls
executable file
·550 lines (517 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
"use strict";
const filterObject = require("filter-obj");
const fs = require("fs").promises;
const path = require("path");
const { R_OK } = require("fs").constants;
const { resolve: localPathResolve } = require("path");
const { resolve: urlPathResolve } = require("path").posix;
const yargs = require("yargs");
const {
BlobServiceClient,
StorageSharedKeyCredential,
generateBlobSASQueryParameters,
SASProtocol,
BlobSASPermissions
} = require("@azure/storage-blob");
const {
downloadFile, uploadFile, uploadAEMMultipartFile,
transferStream,
getResourceHeaders,
AEMUpload,
AEMDownload,
BlockUpload,
BlockDownload
} = require("../index.js");
const BLOB_MIN_BLOCK_SIZE = 64 * 1024; // 64 kb
function createAzureCredential(auth) {
if (!auth || !auth.accountName || !auth.accountKey) {
throw Error("Azure Storage credentials not provided");
}
return new StorageSharedKeyCredential(auth.accountName, auth.accountKey);
}
function createAzureContainerClient(auth, containerName) {
const sharedKeyCredential = createAzureCredential(auth);
const blobServiceClient = new BlobServiceClient(
`https://${auth.accountName}.blob.core.windows.net`,
sharedKeyCredential
);
return blobServiceClient.getContainerClient(containerName);
}
function createAzureSAS(auth, containerName, blobName, perm="r") {
const containerClient = createAzureContainerClient(auth, containerName);
const permissions = new BlobSASPermissions();
permissions.read = perm.includes("r");
permissions.write = perm.includes("w");
permissions.delete = perm.includes("d");
const ONE_HOUR_MS = 60 * 60 * 1000;
const sharedKeyCredential = createAzureCredential(auth);
const blobClient = containerClient.getBlockBlobClient(blobName);
const query = generateBlobSASQueryParameters({
protocol: SASProtocol.Https,
expiresOn: new Date(Date.now() + ONE_HOUR_MS),
containerName,
blobName,
permissions
}, sharedKeyCredential).toString();
return `${blobClient.url}?${query}`;
}
async function commitAzureBlocks(auth, containerName, blobName) {
const containerClient = createAzureContainerClient(auth, containerName);
const blobClient = containerClient.getBlockBlobClient(blobName);
const blockList = await blobClient.getBlockList("uncommitted");
await blobClient.commitBlockList(blockList.uncommittedBlocks.map(x => x.name));
}
async function resolveLocation(value, options) {
if (value.startsWith("https:") || value.startsWith("http:")) {
return {
url: new URL(value)
};
} else if (value.startsWith("azure:")) {
const numParts = options.numParts || Math.ceil(options.size / options.maxPartSize);
const url = new URL(value);
const sasUrl = createAzureSAS(
options.azureAuth,
url.host,
url.pathname.substring(1), // skip the "/" prefix
options.writable ? "cw" : "r"
);
if (numParts > 1) {
const urls = [];
for (let i = 0; i < numParts; ++i) {
// each block id must be the same size
const blockId = Buffer.from(String(i).padStart(10, "0")).toString("base64");
urls.push(`${sasUrl}&comp=block&blockid=${blockId}`);
}
return {
minPartSize: options.minPartSize,
maxPartSize: options.maxPartSize,
urls
};
} else {
return {
url: sasUrl,
headers: {
"x-ms-blob-type": "BlockBlob"
}
};
}
} else {
if (!options.writable) {
await fs.access(value, R_OK);
}
return {
file: value
};
}
}
/**
* Create bulk AEM upload options
*
* @param {String} localFolder Local folder
* @param {String} aemFolderUrl AEM folder url
* @param {*} params Command line parameters
* @returns {AEMUploadOptions} AEM upload options
*/
async function createAEMUploadOptions(localFolder, aemFolderUrl, params) {
const uploadFiles = [];
const nameConflictPolicy = params.nameConflictPolicy || {};
const dir = await fs.opendir(localFolder);
for await (const dirent of dir) {
if (dirent.isFile()) {
const filePath = localPathResolve(localFolder, dirent.name);
const { size: fileSize } = await fs.stat(filePath);
const fileUrl = new URL(urlPathResolve(aemFolderUrl.pathname, dirent.name), aemFolderUrl);
uploadFiles.push({ fileUrl, fileSize, filePath, ...nameConflictPolicy });
}
}
const authorization = "Basic " + Buffer.from(`${params.aemAuth.username}:${params.aemAuth.password}`).toString("base64");
return {
uploadFiles,
headers: {
authorization
},
concurrent: true,
maxConcurrent: params.maxConcurrent,
preferredPartSize: params.partSize
};
}
/**
* Create bulk AEM download options
*
* @param {String} aemFolderUrl AEM folder url
* @param {String} localFolder Local folder url
* @param {*} params
*/
async function createAEMDownloadOptions(aemFolderUrl, localFolder, params) {
const authorization = "Basic " + Buffer.from(`${params.aemAuth.username}:${params.aemAuth.password}`).toString("base64");
const fetch = require("node-fetch-npm");
const response = await fetch(`${aemFolderUrl}.3.json`, {
headers: {
authorization
}
});
const downloadFiles = [];
if (response.ok) {
const json = await response.json();
for (const [ name, value ] of Object.entries(json)) {
if (value["jcr:primaryType"] === "dam:Asset") {
const jcrContent = value["jcr:content"];
const metadata = jcrContent && jcrContent.metadata;
const fileSize = metadata && metadata["dam:size"];
downloadFiles.push({
fileUrl: new URL(path.join(aemFolderUrl.pathname, name), aemFolderUrl),
filePath: path.join(localFolder, name),
fileSize
});
}
}
} else {
throw Error(`Failed to request folder contents from '${aemFolderUrl}': ${response.status}`);
}
return {
downloadFiles,
headers: {
authorization
},
concurrent: true,
maxConcurrent: params.maxConcurrent,
preferredPartSize: params.partSize
};
}
/**
* Download file as multiple blocks
* @param {Location} source source url
* @param {Location} target target path
* @param {*} retryOptions Retry options
*/
async function downloadOneFileAsBlocks(source, target, retryOptions) {
const download = new BlockDownload();
const options = {
downloadFiles: [{
fileUrl: source.url,
filePath: target.path,
fileSize: -1
}],
headers: target.headers,
maxConcurrent: 8,
preferredPartSize: BLOB_MIN_BLOCK_SIZE,
...retryOptions
};
await download.downloadFiles(options);
}
/**
* Upload blocks using one url
* @param {Location} source source path
* @param {Location} target target url
* @param {*} retryOptions Retry options
*/
async function uploadOneBlock(source, target, retryOptions, size) {
const upload = new BlockUpload();
const options = {
uploadFiles: [{
fileUrl: target.url,
filePath: source.file,
fileSize: size
}],
headers: target.headers,
...retryOptions,
concurrent: true,
maxConcurrent: 5,
preferredPartSize: 7
};
await upload.uploadFiles(options);
}
/**
* Upload blocks using many urls
* @param {Location} source source path
* @param {Location} target target url
* @param {*} params Additional request parameters
* @param {*} retryOptions Retry options
*/
async function uploadMultipleBlocks(source, target, params, retryOptions) {
const upload = new BlockUpload();
const options = {
uploadFiles: [{
fileUrl: target.urls,
filePath: source.file,
multipartHeaders: { partHeader: 'test' },
minPartSize: params.minPartSize,
maxPartSize: params.maxPartSize,
partSize: params.partSize,
}],
headers: target.headers,
...retryOptions,
concurrent: true,
maxConcurrent: 5,
preferredPartSize: 7
};
await upload.uploadFiles(options);
console.log("Commit uncommitted blocks");
const url = new URL(params.target);
await commitAzureBlocks(params.azureAuth, url.host, url.pathname.substring(1));
}
async function main() {
// parse command line
const params = yargs
.strict()
.scriptName("npm run testbed --")
.command("$0 <source> <target>", "Testbed for node-httptransfer", yargs =>
yargs
.positional("source", {
describe: "File, URL, or azure://container/path/to/blob to retrieve content from",
type: "string"
})
.positional("target", {
describe: "File, URL, or azure://container/path/to/blob to send content to",
type: "string"
})
.option("partSize", {
describe: "Preferred part size",
type: "number"
})
.option("minPartSize", {
alias: "min",
describe: "Minimum part size",
type: "number",
default: 1
})
.option("maxPartSize", {
alias: "max",
describe: "Maximum part size",
type: "number",
default: 100*1000*1000
})
.option("numParts", {
alias: "n",
describe: "Number of parts",
type: "number"
})
.option("headerGet", {
describe: "Use GET to fetch response headers",
type: "boolean"
})
.option("account-key", {
describe: "Azure storage account key. Environment variable: AZURE_STORAGE_KEY",
type: "string"
})
.option("account-name", {
describe: "Azure storage account name. Environment variable: AZURE_STORAGE_ACCOUNT",
type: "string"
})
.option("aem", {
describe: "Flag to indicate that the source or target URL is an AEM server",
type: "boolean"
})
.option("aem-username", {
describe: "AEM Username. Environment variable: AEM_USERNAME",
type: "string"
})
.option("aem-password", {
describe: "AEM Password. Environment variable: AEM_PASSWORD",
type: "string"
})
.option("retryEnabled", {
describe: "Enable or disable retry on failure",
type: "boolean",
default: true
})
.option("retryAllErrors", {
describe: "Whether or not to retry on all http error codes or just >=500",
type: "boolean",
default: false
})
.option("retryMax", {
describe: "Time to retry until throwing an error (ms)",
type: "number",
default: 60000
})
.option("retryInterval", {
describe: "Time between retries, used by exponential backoff (ms)",
type: "number",
default: 100
})
.option("maxConcurrent", {
describe: "Maximum concurrency for upload and download",
type: "number",
default: 1
})
.option("nameConflictPolicy", {
describe: "Name conflict policy: \"replace\", \"version[,label[,comment]]\"",
type: "string",
coerce: arg => {
if (arg === "replace") {
return {
replace: true
};
} else if (arg.startsWith("version")) {
const values = arg.split(",");
const versionLabel = values.length >= 2 && values[1];
const versionComment = values.length >= 3 && values[2];
return {
createVersion: true,
versionLabel,
versionComment
};
} else {
throw Error(`Unsupported name conflict policy: ${arg}`);
}
},
})
.option("block", {
describe: "Use block transfer upload/download",
type: "boolean",
default: false
})
.example("$0 azure://container/source.txt blob.txt", "Download path/to/source.txt in container to blob.txt")
.example("$0 blob.txt azure://container/target.txt", "Upload blob.txt to path/to/target.txt in container")
.example("$0 azure://container/source.txt azure://container/target.txt", "Transfer source.txt to target.txt in container")
.example("$0 --maxConcurrent 4 --aem ./folder https://localhost:4502/content/dam/folder", "Upload the contents of ./folder to AEM")
.example("$0 --maxConcurrent 4 --aem https://localhost:4502/content/dam/folder ./folder", "Download the contents of /content/dam/folder from AEM")
)
.wrap(yargs.terminalWidth())
.help()
.fail((msg, err, yargs) => {
if (err) {
throw err;
}
console.error(yargs.help());
console.error();
console.error(msg);
process.exit(0);
})
.argv;
// capture azure storage credentials
params.azureAuth = {
accountKey: params["account-key"] || process.env.AZURE_STORAGE_KEY,
accountName: params["account-name"] || process.env.AZURE_STORAGE_ACCOUNT
};
// capture aem credentials
params.aemAuth = {
username: params["aem-username"] || process.env.AEM_USERNAME,
password: params["aem-password"] || process.env.AEM_PASSWORD
};
// capture retry options
const retryOptions = filterObject(
params,
[ "retryEnabled", "retryAllErrors", "retryMax", "retryInterval" ]
);
// resolve source
const source = await resolveLocation(params.source, { ...params, writable: false});
let size;
if (source.url && params.aem) {
// skip since the source references a folder
} else if (source.url) {
const headers = await getResourceHeaders(source.url, {
doGet: params.headerGet,
...retryOptions
});
size = headers.size;
} else if (source.file) {
const stats = await fs.stat(source.file);
size = stats.size;
}
console.log(`Source: ${source.aem || source.url || source.file}, ${size} bytes`);
// resolve target
const target = await resolveLocation(params.target, { ...params, writable: true, size });
if (target.urls) {
console.log(`Target: ${target.urls.length} parts, ${target.urls[0]}`);
} else {
console.log(`Target: ${target.aem || target.url || target.file}`);
}
if(params.block) {
console.log("Testing block upload transfer");
if (source.url && target.file) {
console.log("Downloading as blocks");
await downloadOneFileAsBlocks(source, target, retryOptions);
} else if (source.file && target.url) {
console.log("Uploading using one block url");
await uploadOneBlock(source, target, retryOptions, size);
} else if (source.file && target.urls) {
//multi-part upload
console.log("Uploading using multi-part urls");
await uploadMultipleBlocks(source, target, params, retryOptions, size);
} else {
throw Error("Transfer is not supported");
}
} else {
// transfer
if (params.aem && source.file && target.url) {
const options = await createAEMUploadOptions(source.file, target.url, params);
const upload = new AEMUpload();
upload.on("filestart", ({ fileName, fileSize }) => {
console.log(`${fileName}: Start transfer ${fileSize} bytes`);
});
upload.on("fileprogress", ({ fileName, fileSize, transferred }) => {
console.log(`${fileName}: Transferred ${transferred}/${fileSize} bytes`);
});
upload.on("fileend", ({ fileName, fileSize }) => {
console.log(`${fileName}: Complete transfer ${fileSize} bytes`);
});
upload.on("fileerror", ({ fileName, errors }) => {
console.log(`${fileName}: FAILED --> ${errors[0].message}`);
});
await upload.uploadFiles(options);
} else if (params.aem && source.url && target.file) {
const options = await createAEMDownloadOptions(source.url, target.file, params);
const download = new AEMDownload();
download.on("filestart", ({ fileName, fileSize }) => {
console.log(`${fileName}: Start transfer ${fileSize} bytes`);
});
download.on("fileprogress", ({ fileName, fileSize, transferred }) => {
console.log(`${fileName}: Transferred ${transferred}/${fileSize} bytes`);
});
download.on("fileend", ({ fileName, fileSize }) => {
console.log(`${fileName}: Complete transfer ${fileSize} bytes`);
});
download.on("fileerror", ({ fileName, errors }) => {
console.log(`${fileName}: FAILED --> ${errors[0].message}`);
});
await download.downloadFiles(options);
} else if (params.aem) {
throw Error("Transfer not supported");
} else if (source.file && target.url) {
await uploadFile(source.file, target.url, {
headers: target.headers,
...retryOptions
});
} else if (source.url && target.file) {
await downloadFile(source.url, target.file, {
mkdirs: true,
...retryOptions
});
} else if (source.url && target.url) {
await transferStream(source.url, target.url, {
target: {
headers: target.headers
},
...retryOptions
});
} else if (source.file && target.urls) {
await uploadAEMMultipartFile(source.file, target, {
...retryOptions,
partSize: params.partSize,
maxConcurrent: params.maxConcurrent || 1
});
console.log("Commit uncommitted blocks");
const url = new URL(params.target);
await commitAzureBlocks(params.azureAuth, url.host, url.pathname.substring(1));
} else {
throw Error("Transfer is not supported");
}
}
}
main()
.catch(err => {
console.error(err);
});