This repository has been archived by the owner on Sep 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathadvanced.js
677 lines (558 loc) · 27.7 KB
/
advanced.js
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//----------------------------------------------------------------------------------
var guid = require('node-uuid');
var util = require('util');
var storage = require('azure-storage');
var config = require('./config');
function advancedSamples() {
return scenarios = [
{
action: leaseBlob,
message: 'Blob Lease Sample Completed\n'
},
{
action: leaseContainer,
message: 'Container Lease Sample Completed\n'
},
{
action: setCorsRules,
message: 'Cors Rules Sample Completed\n'
},
{
action: containerOperations,
message: 'Containers Sample Completed\n'
},
{
action: copyBlob,
message: 'Copy Blob Sample Completed\n'
},
{
action: containerOperationsWithSas,
message: 'Containers Sample with SAS Completed\n'
},
{
action: serviceProperties,
message: 'Service Properties Sample Completed\n'
},
{
action: containerProperties,
message: 'Container Properties Sample Completed\n'
},
{
action: containerMetadata,
message: 'Container Metadata Sample Completed\n'
},
{
action: containerAcl,
message: 'Container Access Policy Sample Completed\n'
},
{
action: blobProperties,
message: 'Blob Properties Sample Completed\n'
},
{
action: blobMetadata,
message: 'Blob Metadata Sample Completed\n'
}
];
}
function copyBlob(callback) {
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
console.log('2. Creating Text Blob');
blobService.createBlockBlobFromText(containerName, 'sourceBlob', 'sample data', function (error) {
if (error) return callback(error);
var sourceBlobUrl = blobService.getUrl(containerName, 'sourceBlob');
console.log('3. Copying Text Blob');
blobService.startCopyBlob(sourceBlobUrl, containerName, 'targetBlob', function (error, result) {
if (error) return callback(error);
console.log('status ' + result.copy.status);
if (result.copy.status === 'pending') {
console.log('4. Aborting Text Blob Copy');
blobService.abortCopyBlob(containerName, 'targetBlob', result.copy.id, function (error) {
if (error) callback(error);
console.log('Copy operation aborted');
//Delete container
console.log('5. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
})
})
} else {
//Delete container
console.log('4. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
})
}
})
})
});
}
function containerOperations(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// List all the containers within the storage account.
console.log('2. List Container');
listContainers('demoblobcontainer', blobService, null, null, null, function (error, results) {
if (error) return callback(error);
for (var i = 0; i < results.length; i++) {
console.log(util.format(' - %s'), results[i].name);
}
//Delete container
console.log('3. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
}
function setCorsRules(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
blobService.getServiceProperties(function (error, properties) {
if (error) return callback(error);
var originalCors = properties.Cors;
properties.Cors = {
CorsRule: [{
AllowedOrigins: ['*'],
AllowedMethods: ['POST', 'GET'],
AllowedHeaders: ['*'],
ExposedHeaders: ['*'],
MaxAgeInSeconds: 3600
}]
};
blobService.setServiceProperties(properties, function (error) {
if (error) return callback(error);
// reverts the cors rules back to the original ones so they do not get corrupted by the ones set in this sample
properties.Cors = originalCors;
blobService.setServiceProperties(properties, function (error) {
return callback(error);
});
});
});
}
function leaseContainer(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoleaseblobcontainer-" + guid.v1();
console.log('1. Create Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
console.log('2. Acquire Lease on container');
blobService.acquireLease(containerName, null, { leaseDuration: 15 }, function (error, leaseResult) {
if (error) return callback(error);
console.log('3. Delete Container without lease');
blobService.deleteContainer(containerName, function (error) {
if (error) {
console.log('The container can not be deleted. A lease was not specified. ' + error.message);
}
console.log('4. Delete Container with lease ' + leaseResult.id);
blobService.deleteContainer(containerName, { leaseId: leaseResult.id }, function (error) {
return callback(error);
})
});
});
});
}
function leaseBlob(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoleaseblobcontainer-" + guid.v1();
var blobName = 'exclusive';
console.log('1. Create Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
console.log('2. Create blob');
blobService.createBlockBlobFromText(containerName, blobName, 'blob created', function (error) {
if (error) return callback(error);
console.log('3. Acquire lease on blob');
blobService.acquireLease(containerName, blobName, { leaseDuration: 15 }, function (error, leaseResult) {
if (error) return callback(error);
console.log('4. Delete blob without a lease');
blobService.deleteBlob(containerName, blobName, function (error) {
if (error) {
console.log('The blob can not be deleted. A lease was not specified. ' + error.message);
}
console.log('5. Delete blob with lease id ' + leaseResult.id);
blobService.deleteBlob(containerName, blobName, { leaseId: leaseResult.id }, function (error) {
if (error) return callback(error);
console.log('6. Delete container');
blobService.deleteContainer(containerName, function (error) {
return callback(error);
})
})
})
})
})
});
}
function containerOperationsWithSas(callback) {
var containerName = "demosasblobcontainer-" + guid.v1();
var blobName = 'blobsas';
var blobService = storage.createBlobService(config.connectionString);
console.log('1. Creating container')
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
console.log('2. Getting Shared Access Signature for container');
var expiryDate = new Date();
expiryDate.setMinutes(expiryDate.getMinutes() + 30);
var sharedAccessPolicy = {
AccessPolicy: {
Permissions: storage.BlobUtilities.SharedAccessPermissions.READ +
storage.BlobUtilities.SharedAccessPermissions.WRITE +
storage.BlobUtilities.SharedAccessPermissions.DELETE +
storage.BlobUtilities.SharedAccessPermissions.LIST,
Expiry: expiryDate
}
};
var sas = blobService.generateSharedAccessSignature(containerName, null, sharedAccessPolicy);
var sharedBlobService = storage.createBlobServiceWithSas(blobService.host, sas);
console.log('3. Creating blob with Shared Access Signature');
sharedBlobService.createBlockBlobFromText(containerName, blobName, 'test data', function (error) {
if (error) return callback(error);
console.log('4. Listing blobs in container with Shared Access Signature');
listBlobs(sharedBlobService, containerName, null, null, null, function (error, blobs) {
if (error) return callback(error);
console.log('5. Deleting blob with Shared Access Signature');
sharedBlobService.deleteBlob(containerName, blobName, function (error) {
if (error) return callback(error);
console.log('6. Deleting container');
blobService.deleteContainer(containerName, function (error) {
return callback(error);
})
})
})
})
});
}
// Set logging and metrics service properties
function serviceProperties(callback) {
// Create a blob client for interacting with the blob service from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
var blobService = storage.createBlobService(config.connectionString);
blobService.getServiceProperties(function (error, properties) {
if (error) return callback(error);
var originalProperties = properties;
properties = serviceProperties = {
Logging: {
Version: '1.0',
Delete: true,
Read: true,
Write: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
},
HourMetrics: {
Version: '1.0',
Enabled: true,
IncludeAPIs: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
},
MinuteMetrics: {
Version: '1.0',
Enabled: true,
IncludeAPIs: true,
RetentionPolicy: {
Enabled: true,
Days: 10,
},
}
};
blobService.setServiceProperties(properties, function (error) {
if (error) return callback(error);
// reverts the cors rules back to the original ones so they do not get corrupted by the ones set in this sample
blobService.setServiceProperties(originalProperties, function (error) {
return callback(error);
});
});
});
}
// Retrieve statistics related to replication for the Blob service.
// This operation is only available on the secondary location endpoint when read-access geo-redundant replication is enabled for the storage account.
function serviceStats(callback){
var blobService = storage.createBlobService(config.connectionString);
blobService.getServiceStats(function (error, serviceStats){
if(error) return callback(error);
if(serviceStats != null && serviceStats.GeoReplication != null)
console.log('Geo replication status: ' + serviceStats.GeoReplication.Status);
return callback(null);
});
}
// Get system properties of a container
function containerProperties(callback){
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// List all the containers within the storage account.
console.log('2. Get Container Properties');
blobService.getContainerProperties(containerName, function (error, container, response) {
if(error) return callback(error);
console.log('request id: ', container.requestId);
console.log('name: ', container.name);
console.log('last modified: ', container.lastModified);
console.log('lease status: ', container.lease.status);
console.log('lease state: ', container.lease.state);
//Delete container
console.log('3. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
}
// Manage user-defined metadata of a container
function containerMetadata(callback){
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// Set container metadata
var metadata = { 'Color': 'Blue', 'Foo': 'Bar' };
console.log('2. Set Container Metadata');
blobService.setContainerMetadata(containerName, metadata, function (error, result, response) {
// Get container metadata
console.log('3. Get Container Metadata');
blobService.getContainerMetadata(containerName, function (error, result, response) {
if(error) return callback(error);
console.log('Metadata:');
console.log(' Color: ', result.metadata.color);
console.log(' Foo: ', result.metadata.foo);
//Delete container
console.log('4. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
});
}
// Manage the public access policy and any stored access policies for the container
function containerAcl(callback){
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// Set container metadata
var options = {publicAccessLevel: storage.BlobUtilities.BlobContainerPublicAccessType.CONTAINER};
console.log('2. Set Container Acl');
blobService.setContainerAcl(containerName, null, options, function (error, result, response) {
if(error) return callback(error);
// Get container Acl
console.log('3. Get Container Acl');
blobService.getContainerAcl(containerName, function (error, result, response) {
if(error) return callback(error);
console.log('Public access level: ', result.publicAccessLevel);
//Delete container
console.log('4. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
});
}
// Manage system properties on the blob
function blobProperties(callback){
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
// Create Container
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// Create Blob
var text = 'hello';
var blobName = 'blob-' + guid.v1();
console.log('2. Creating Blob');
blobService.createBlockBlobFromText(containerName, blobName, text, function (error) {
if (error) return callback(error);
var properties = {};
properties.contentType = 'text';
properties.contentEncoding = 'utf8';
properties.contentLanguage = 'pt';
properties.cacheControl = 'true';
properties.contentDisposition = 'attachment';
// Set blob properties
console.log('3. Set Blob Properties');
blobService.setBlobProperties(containerName, blobName, properties, function (error) {
if (error) return callback(error);
// Get blob properties
console.log('4. Get Blob Properties');
blobService.getBlobProperties(containerName, blobName, function (error, blob) {
if (error) return callback(error);
console.log(' Length: ' + blob.contentLength);
console.log(' Content Type: ' + blob.contentSettings.contentType);
console.log(' Content Encoding: ' + blob.contentSettings.contentEncoding);
console.log(' Content Language: ' + blob.contentSettings.contentLanguage);
console.log(' Content Disposition: ' + blob.contentSettings.contentDisposition);
console.log(' Cache Control: ' + blob.contentSettings.cacheControl);
// Delete blob
console.log('5. Delete Blob');
blobService.deleteBlob(containerName, blobName, function (error) {
if (error) return callback(error);
// Delete container
console.log('6. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
});
});
});
}
// Manage user-defined metadata of a blob
function blobMetadata(callback){
var blobService = storage.createBlobService(config.connectionString);
var containerName = "demoblobcontainer-" + guid.v1();
// Create Container
console.log('1. Creating Container');
blobService.createContainerIfNotExists(containerName, function (error) {
if (error) return callback(error);
// Create Blob
var text = 'hello';
var blobName = 'blob-' + guid.v1();
console.log('2. Creating Blob');
blobService.createBlockBlobFromText(containerName, blobName, text, function (error) {
if (error) return callback(error);
var metadata = { Color: 'Blue', Foo: 'Bar'};
// Set blob metadata
console.log('3. Set Blob Metadata');
blobService.setBlobMetadata(containerName, blobName, metadata, function (error) {
if (error) return callback(error);
// Get blob metadata
console.log('4. Get Blob Metadata');
blobService.getBlobMetadata(containerName, blobName, function (error, result) {
if (error) return callback(error);
console.log(' Color: ' + result.metadata.color);
console.log(' Foo: ' + result.metadata.foo);
// Delete blob
console.log('5. Delete Blob');
blobService.deleteBlob(containerName, blobName, function (error) {
if (error) return callback(error);
// Delete container
console.log('6. Delete Container');
blobService.deleteContainerIfExists(containerName, function (error) {
callback(error);
});
});
});
});
});
});
}
/**
* Lists containers in account.
* @ignore
*
* @param {string} prefix The prefix of the container.
* @param {BlobService} blobService The blob service client.
* @param {object} token A continuation token returned by a previous listing operation.
* Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.maxResults] Specifies the maximum number of containers to return per call to Azure storage.
* @param {string} [options.include] Include this parameter to specify that the container's metadata be returned as part of the response body. (allowed values: '', 'metadata')
* **Note** that all metadata names returned from the server will be converted to lower case by NodeJS itself as metadata is set via HTTP headers and HTTP header names are case insensitive.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of `[containers]{@link ContainerResult}` and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
function listContainers(prefix, blobService, token, options, containers, callback) {
containers = containers || [];
blobService.listContainersSegmentedWithPrefix(prefix, token, options, function (error, result) {
if (error) return callback(error);
containers.push.apply(containers, result.entries);
var token = result.continuationToken;
if (token) {
console.log(' Received a segment of results. There are ' + result.entries.length + ' containers on this segment.');
listContainers(prefix, blobService, token, options, containers, callback);
} else {
console.log(' Completed listing. There are ' + containers.length + ' containers.');
callback(null, containers);
}
});
}
/**
* Lists blobs in the container.
* @ignore
*
* @param {BlobService} blobService The blob service client.
* @param {string} container The container name.
* @param {object} token A continuation token returned by a previous listing operation.
* Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {int} [options.maxResults] Specifies the maximum number of directories to return per call to Azure ServiceClient.
* This does NOT affect list size returned by this function. (maximum: 5000)
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information
* if an error occurs; otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of directories and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
function listBlobs(blobService, container, token, options, blobs, callback) {
blobs = blobs || [];
blobService.listBlobsSegmented(container, token, options, function (error, result) {
if (error) return callback(error);
blobs.push.apply(blobs, result.entries);
var token = result.continuationToken;
if (token) {
console.log(' Received a segment of results. There are ' + result.entries.length + ' blobs on this segment.');
listBlobs(blobService, container, token, options, blobs, callback);
} else {
console.log(' Completed listing. There are ' + blobs.length + ' blobs.');
callback(null, blobs);
}
});
}
module.exports = advancedSamples();