azure-storage
Version:
Microsoft Azure Storage Client Library for Node.js
731 lines (646 loc) • 409 kB
JavaScript
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed 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 CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Module dependencies.
var qs = require('querystring');
var url = require('url');
var util = require('util');
var _ = require('underscore');
var extend = require('extend');
var azureCommon = require('./../../common/common.core');
var BlockRangeStream = require('./internal/blockrangestream');
var Md5Wrapper = require('./../../common/md5-wrapper');
var PageRangeStream = require('./internal/pagerangestream');
var RangeStream = require('./../../common/streams/rangestream');
var azureutil = azureCommon.util;
var SR = azureCommon.SR;
var validate = azureCommon.validate;
var StorageServiceClient = azureCommon.StorageServiceClient;
var WebResource = azureCommon.WebResource;
// Constants
var Constants = azureCommon.Constants;
var BlobConstants = Constants.BlobConstants;
var HeaderConstants = Constants.HeaderConstants;
var QueryStringConstants = Constants.QueryStringConstants;
var RequestLocationMode = Constants.RequestLocationMode;
// Streams
var BatchOperation = azureCommon.BatchOperation;
var SpeedSummary = azureCommon.SpeedSummary;
var ChunkAllocator = azureCommon.ChunkAllocator;
var ChunkStream = azureCommon.ChunkStream;
var ChunkStreamWithStream = azureCommon.ChunkStreamWithStream;
// Models requires
var AclResult = azureCommon.AclResult;
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var BlockListResult = require('./models/blocklistresult');
var BlobResult = require('./models/blobresult');
var ContainerResult = require('./models/containerresult');
var LeaseResult = require('./models/leaseresult');
var BlobUtilities = require('./blobutilities');
// Errors requires
var errors = require('../../common/errors/errors');
var ArgumentError = errors.ArgumentError;
var ArgumentNullError = errors.ArgumentNullError;
var StorageError = errors.StorageError;
/**
* Creates a new BlobService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The BlobService class is used to perform operations on the Microsoft Azure Blob Service.
* The Blob Service provides storage for binary large objects, and provides
* functions for working with data stored in blobs as either streams or pages of data.
*
* For more information on the Blob Service, as well as task focused information on using it in a Node.js application, see
* [How to Use the Blob Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-blob-storage/).
* The following defaults can be set on the blob service.
* singleBlobPutThresholdInBytes The default maximum size, in bytes, of a blob before it must be separated into blocks.
* defaultEnableReuseSocket The default boolean value to enable socket reuse when uploading local files or streams.
* If the Node.js version is lower than 0.10.x, socket reuse will always be turned off.
* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Blob service.
* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Blob service.
* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Blob service.
* defaultLocationMode The default location mode for requests made via the Blob service.
* parallelOperationThreadCount The number of parallel operations that may be performed when uploading a blob that is greater than
* the value specified by the singleBlobPutThresholdInBytes property in size.
* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Blob service; true to use the
* Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString] The storage account or the connection string.
* @param {string} [storageAccessKey] The storage access key.
* @param {string|object} [host] The host address. To define primary only, pass a string.
* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {string} [endpointSuffix] The endpoint suffix.
*/
function BlobService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
BlobService['super_'].call(this,
storageServiceSettings._name,
storageServiceSettings._key,
storageServiceSettings._blobEndpoint,
storageServiceSettings._usePathStyleUri,
storageServiceSettings._sasToken);
this.defaultEnableReuseSocket = Constants.DEFAULT_ENABLE_REUSE_SOCKET;
this.singleBlobPutThresholdInBytes = BlobConstants.DEFAULT_SINGLE_BLOB_PUT_THRESHOLD_IN_BYTES;
this.parallelOperationThreadCount = Constants.DEFAULT_PARALLEL_OPERATION_THREAD_COUNT;
}
util.inherits(BlobService, StorageServiceClient);
// Non-class methods
/**
* Create resource name
* @ignore
*
* @param {string} containerName Container name
* @param {string} blobName Blob name
* @return {string} The encoded resource name.
*/
function createResourceName(containerName, blobName, forSAS) {
// Resource name
if (blobName && !forSAS) {
blobName = encodeURIComponent(blobName);
blobName = blobName.replace(/%2F/g, '/');
blobName = blobName.replace(/%5C/g, '/');
blobName = blobName.replace(/\+/g, '%20');
}
// return URI encoded resource name
if (blobName) {
return containerName + '/' + blobName;
}
else {
return containerName;
}
}
// Blob service methods
/**
* Gets the service stats for a storage account’s Blob service.
*
* @this {BlobService}
* @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.timeoutIntervalInMs] The timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ServiceStats}` will contain the stats and
* `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceStats = function (optionsOrCallback, callback) {
var options;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { options = o; callback = c; });
validate.validateArgs('getServiceStats', function (v) {
v.callback(callback);
});
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'stats')
.withQueryOption(QueryStringConstants.RESTYPE, 'service');
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
var processResponseCallback = function (responseObject, next) {
responseObject.serviceStatsResult = null;
if (!responseObject.error) {
responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
}
// function to be called after all filters
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
};
// call the first filter
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Gets the properties of a storage account’s Blob service, including Azure Storage Analytics.
*
* @this {BlobService}
* @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.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ServiceProperties}` will contain the properties
* and `response` will contain information related to this operation.
*/
BlobService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
return this.getAccountServiceProperties(optionsOrCallback, callback);
};
/**
* Sets the properties of a storage account's Blob service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {BlobService}
* @param {object} serviceProperties The service properties.
* @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.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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 {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise, `response`
* will contain information related to this operation.
*/
BlobService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
/**
* Sets the tier of a blockblob under a blob storage LRS account, or the tier of a pageblob under a premium storage account.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {string} blob The blob name.
* @param {string} blobTier Please see BlobUtilities.BlobTier.StandardBlobTier or BlobUtilities.BlobTier.PremiumPageBlobTier for possible values.
* @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.clientRequestTimeoutInMs] The timeout of client requests, 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 {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise, `response`
* will contain information related to this operation.
*/
BlobService.prototype.setBlobTier = function (container, blob, blobTier, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setBlobTier', function (v) {
v.string(container, 'container');
v.string(blob, 'blob');
v.string(blobTier, 'blobTier');
v.containerNameIsValid(container);
v.blobNameIsValid(container, blob);
v.blobTierNameIsValid(blobTier);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var resourceName = createResourceName(container, blob);
var webResource = WebResource.put(resourceName)
.withQueryOption(QueryStringConstants.COMP, 'tier')
.withHeader(HeaderConstants.ACCESS_TIER, blobTier);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Lists a segment containing a collection of container items under the specified account.
*
* @this {BlobService}
* @param {object} currentToken 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.clientRequestTimeoutInMs] The timeout of client requests, 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.
*/
BlobService.prototype.listContainersSegmented = function (currentToken, optionsOrCallback, callback) {
this.listContainersSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of container items whose names begin with the specified prefix under the specified account.
*
* @this {BlobService}
* @param {string} prefix The prefix of the container name.
* @param {object} currentToken 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.clientRequestTimeoutInMs] The timeout of client requests, 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.
*/
BlobService.prototype.listContainersSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listContainers', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'list')
.withQueryOption(QueryStringConstants.MAX_RESULTS, options.maxResults)
.withQueryOption(QueryStringConstants.INCLUDE, options.include);
if (!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(QueryStringConstants.MARKER, currentToken.nextMarker);
}
webResource.withQueryOption(QueryStringConstants.PREFIX, prefix);
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.listContainersResult = null;
if (!responseObject.error) {
responseObject.listContainersResult = {
entries: null,
continuationToken: null
};
responseObject.listContainersResult.entries = [];
var containers = [];
if (responseObject.response.body.EnumerationResults.Containers && responseObject.response.body.EnumerationResults.Containers.Container) {
containers = responseObject.response.body.EnumerationResults.Containers.Container;
if (!_.isArray(containers)) {
containers = [containers];
}
}
containers.forEach(function (currentContainer) {
var containerResult = ContainerResult.parse(currentContainer);
responseObject.listContainersResult.entries.push(containerResult);
});
if (responseObject.response.body.EnumerationResults.NextMarker) {
responseObject.listContainersResult.continuationToken = {
nextMarker: null,
targetLocation: null
};
responseObject.listContainersResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;
responseObject.listContainersResult.continuationToken.targetLocation = responseObject.targetLocation;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.listContainersResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
// Container methods
/**
* Checks whether or not a container exists on the service.
*
* @this {BlobService}
* @param {string} container The container name.
* @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.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ContainerResult}` will contain
* the container information including `exists` boolean member.
* `response` will contain information related to this operation.
*/
BlobService.prototype.doesContainerExist = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('doesContainerExist', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
this._doesContainerExist(container, false, options, callback);
};
/**
* Creates a new container under the specified account.
* If a container with the same name already exists, the operation fails.
*
* @this {BlobService}
* @param {string} container The container name.
* @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 {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ContainerResult}` will contain
* the container information.
* `response` will contain information related to this operation.
*/
BlobService.prototype.createContainer = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createContainer', function (v) {
v.string(container, 'container');
v.test(function () { return container !== '$logs'; },
'Container name format is incorrect');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.put(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container');
webResource.addOptionalMetadataHeaders(options.metadata);
webResource.withHeader(HeaderConstants.BLOB_PUBLIC_ACCESS, options.publicAccessLevel);
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
if (options.metadata) {
responseObject.containerResult.metadata = options.metadata;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Creates a new container under the specified account if the container does not exists.
*
* @this {BlobService}
* @param {string} container The container name.
* @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 {object} [options.metadata] The metadata key/value pairs.
* @param {string} [options.publicAccessLevel] Specifies whether data in the container may be accessed publicly and the level of access.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ContainerResult}` will contain
* the container information including `created` boolean member.
* `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var blobService = azure.createBlobService();
* blobService.createContainerIfNotExists('taskcontainer', {publicAccessLevel : 'blob'}, function(error) {
* if(!error) {
* // Container created or exists, and is public
* }
* });
*/
BlobService.prototype.createContainerIfNotExists = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createContainerIfNotExists', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesContainerExist(container, true, options, function (error, result, response) {
var exists = result.exists;
result.created = false;
delete result.exists;
if (error) {
callback(error, result, response);
} else if (exists) {
response.isSuccessful = true;
callback(error, result, response);
} else {
self.createContainer(container, options, function (createError, containerResult, createResponse) {
if (!createError) {
containerResult.created = true;
}
else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS) {
// If it was created before, there was no actual error.
createError = null;
createResponse.isSuccessful = true;
}
callback(createError, containerResult, createResponse);
});
}
});
};
/**
* Retrieves a container and its properties from a specified account.
* **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.
*
* @this {BlobService}
* @param {string} container The container name.
* @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 {string} [options.leaseId] The container lease identifier.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ContainerResult}` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerProperties = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getContainerProperties', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.head(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Returns all user-defined metadata for the container.
* **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.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @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.clientRequestTimeoutInMs] The timeout of client requests, 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]{@link ContainerResult}` will contain
* information for the container.
* `response` will contain information related to this operation.
*/
BlobService.prototype.getContainerMetadata = function (container, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getContainerMetadata', function (v) {
v.string(container, 'container');
v.containerNameIsValid(container);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.head(container)
.withQueryOption(QueryStringConstants.RESTYPE, 'container')
.withQueryOption(QueryStringConstants.COMP, 'metadata')
.withHeader(HeaderConstants.LEASE_ID, options.leaseId);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var self = this;
var processResponseCallback = function (responseObject, next) {
responseObject.containerResult = null;
if (!responseObject.error) {
responseObject.containerResult = new ContainerResult(container);
responseObject.containerResult.metadata = self.parseMetadataHeaders(responseObject.response.headers);
responseObject.containerResult.getPropertiesFromHeaders(responseObject.response.headers);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.containerResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Sets the container's metadata.
*
* Calling the Set Container Metadata operation overwrites all existing metadata that is associated with the container.
* It's not possible to modify an individual name/value pair.
*
* @this {BlobService}
* @param {string} container The container name.
* @param {object} metadata The metadata key/value pairs.
* @param {object} [options] The request options.
* @param {string} [options.leaseId] The container lease identifier.
* @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 {AccessConditions} [options.accessConditions] The access conditions.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, 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 {errorOrResponse} callback `error` will contain information
* if an error occurs; otherwise
*