use of com.microsoft.azure.storage.blob.CloudBlobClient in project nifi by apache.
the class DeleteAzureBlobStorage method onTrigger.
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final long startNanos = System.nanoTime();
String containerName = context.getProperty(AzureStorageUtils.CONTAINER).evaluateAttributeExpressions(flowFile).getValue();
String blobPath = context.getProperty(BLOB).evaluateAttributeExpressions(flowFile).getValue();
try {
CloudBlobClient blobClient = AzureStorageUtils.createCloudBlobClient(context, getLogger(), flowFile);
CloudBlobContainer container = blobClient.getContainerReference(containerName);
CloudBlob blob = container.getBlockBlobReference(blobPath);
blob.deleteIfExists();
session.transfer(flowFile, REL_SUCCESS);
final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
session.getProvenanceReporter().send(flowFile, blob.getSnapshotQualifiedUri().toString(), transferMillis);
} catch (StorageException | URISyntaxException e) {
getLogger().error("Failed to delete the specified blob {} from Azure Storage. Routing to failure", new Object[] { blobPath }, e);
flowFile = session.penalize(flowFile);
session.transfer(flowFile, REL_FAILURE);
}
}
use of com.microsoft.azure.storage.blob.CloudBlobClient in project jackrabbit-oak by apache.
the class Utils method getBlobClient.
/**
* Create CloudBlobClient from properties.
*
* @param connectionString connectionString to configure @link {@link CloudBlobClient}
* @return {@link CloudBlobClient}
*/
public static CloudBlobClient getBlobClient(final String connectionString) throws URISyntaxException, InvalidKeyException {
CloudStorageAccount account = CloudStorageAccount.parse(connectionString);
CloudBlobClient client = account.createCloudBlobClient();
return client;
}
use of com.microsoft.azure.storage.blob.CloudBlobClient in project photon-model by vmware.
the class AzureInstanceService method deleteVHDBlobsInAzure.
private DeferredResult<Void> deleteVHDBlobsInAzure(AzureInstanceContext ctx) {
if (isManagedDisk().test(ctx.bootDiskState)) {
return DeferredResult.completed(null);
}
String defaultSAName = ctx.bootDiskState.storageDescription.name;
String defaultSAKey = ctx.storageAccountKeysForDisks.get(ctx.bootDiskState.storageDescription.authCredentialsLink);
List<DiskService.DiskStateExpanded> diskStatesToDelete = ctx.dataDiskStates.stream().filter(disk -> disk.persistent == false).collect(Collectors.toList());
if (ctx.bootDiskState.persistent == false) {
diskStatesToDelete.add(ctx.bootDiskState);
}
OperationContext opCtx = OperationContext.getOperationContext();
// Create DR
DeferredResult<Void> dr = new DeferredResult<>();
CompletableFuture.runAsync(() -> {
diskStatesToDelete.forEach(disk -> {
try {
CloudStorageAccount storageAccountOfVHDBlob;
if (disk.storageDescription == null) {
storageAccountOfVHDBlob = CloudStorageAccount.parse(String.format(STORAGE_CONNECTION_STRING, defaultSAName, defaultSAKey));
} else {
String key = ctx.storageAccountKeysForDisks.get(disk.storageDescription.authCredentialsLink);
storageAccountOfVHDBlob = CloudStorageAccount.parse(String.format(STORAGE_CONNECTION_STRING, disk.storageDescription.name, key));
}
CloudBlobClient client = storageAccountOfVHDBlob.createCloudBlobClient();
CloudBlobContainer container = client.getContainerReference("vhds");
String vhdBlobName = disk.id.substring(disk.id.lastIndexOf("/") + 1);
CloudPageBlob blob = container.getPageBlobReference(vhdBlobName);
blob.deleteIfExists();
} catch (URISyntaxException | InvalidKeyException | StorageException e) {
logSevere("Unable to delete VHD file for disk [%s] because of %s ", disk.name, e.toString());
}
});
}, getHost().allocateExecutor(this)).whenComplete((obj, throwable) -> {
OperationContext.restoreOperationContext(opCtx);
dr.complete(obj);
});
return dr;
}
use of com.microsoft.azure.storage.blob.CloudBlobClient in project photon-model by vmware.
the class TestAzureDeleteTask method testProvisionWithPersistentUnmanagedDisk.
/**
* Creates a Azure unmanaged instance with persist options for disks. Checks if VHD blob cleanup happens according to the persist flag.
*/
@Test
public void testProvisionWithPersistentUnmanagedDisk() throws Throwable {
BaseComputeInstanceContext.ImageSource imageSource = createImageSource(getHost(), this.endpointState, IMAGE_REFERENCE);
// Create a Azure VM compute resource with 2 additional disks.
int numberOfAdditionalDisks = 3;
AzureTestUtil.VMResourceSpec vmResourceSpec = new AzureTestUtil.VMResourceSpec(getHost(), this.computeHost, this.endpointState, azureVMName).withImageSource(imageSource).withNicSpecs(DEFAULT_NIC_SPEC).withNumberOfAdditionalDisks(numberOfAdditionalDisks).withPersistentDisks(AzureTestUtil.VMResourceSpec.PersistentDisks.SOME).withExistingStorageAccount(storageAccountName, resourceGroupName).withManagedDisk(false);
// create Azure VM compute resource.
this.vmState = createVMResourceFromSpec(vmResourceSpec);
kickOffProvisionTask();
List<DiskService.DiskState> diskStates = this.vmState.diskLinks.stream().map(diskLink -> getHost().getServiceState(null, DiskService.DiskState.class, UriUtils.buildUri(getHost(), diskLink))).collect(Collectors.toList());
int computeStatesToRemain = 1;
deleteVMs(getHost(), this.vmState.documentSelfLink, this.isMock, computeStatesToRemain);
// assertions
if (!this.isMock) {
Azure az = getAzureSdkClients().getAzureClient();
String key = az.storageAccounts().getByResourceGroup(resourceGroupName, storageAccountName).getKeys().get(0).value();
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.parse(String.format(STORAGE_CONNECTION_STRING, storageAccountName, key));
CloudBlobClient client = cloudStorageAccount.createCloudBlobClient();
CloudBlobContainer container = client.getContainerReference("vhds");
for (DiskService.DiskState diskState : diskStates) {
String vhdBlobName = diskState.id.substring(diskState.id.lastIndexOf("/") + 1);
CloudPageBlob blob = container.getPageBlobReference(vhdBlobName);
assertEquals("Disk VHD blob should persist", diskState.persistent, blob.exists());
}
}
}
use of com.microsoft.azure.storage.blob.CloudBlobClient in project photon-model by vmware.
the class AzureComputeHostStorageStatsGatherer method getBlobUsedBytesAsync.
private void getBlobUsedBytesAsync(AzureStorageStatsDataHolder statsData, StorageMetricsStages next) {
Runnable getBlobsAsync = () -> {
String metricName = PhotonModelConstants.STORAGE_USED_BYTES;
List<ServiceStats.ServiceStat> statDatapoints = new ArrayList<>();
AtomicInteger accountsCount = new AtomicInteger(statsData.storageAccounts.size());
final List<Throwable> exs = new ArrayList<>();
for (Map.Entry<String, StorageAccount> account : statsData.storageAccounts.entrySet()) {
String resourceGroupName = getResourceGroupName(account.getValue().id);
statsData.azureClients.getAzureClient().storageAccounts().inner().listKeysAsync(resourceGroupName, account.getValue().name, new AzureAsyncCallback<StorageAccountListKeysResultInner>() {
@Override
public void onError(Throwable e) {
handleError(statsData, e);
}
@Override
public void onSuccess(StorageAccountListKeysResultInner result) {
logFine(() -> String.format("Retrieved the storage account keys for" + " storage account [%s].", account.getValue().name));
String storageConnectionString = String.format(STORAGE_CONNECTION_STRING, account.getValue().name, result.keys().get(0).value());
try {
CloudStorageAccount storageAccount = getAzureStorageClient(storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
ResultContinuation nextContainerResults = null;
do {
ResultSegment<CloudBlobContainer> contSegment = blobClient.listContainersSegmented(null, ContainerListingDetails.NONE, QUERY_RESULT_LIMIT, nextContainerResults, null, null);
nextContainerResults = contSegment.getContinuationToken();
for (CloudBlobContainer container : contSegment.getResults()) {
ResultContinuation nextBlobResults = null;
do {
ResultSegment<ListBlobItem> blobsSegment = container.listBlobsSegmented(null, false, EnumSet.noneOf(BlobListingDetails.class), QUERY_RESULT_LIMIT, nextBlobResults, null, null);
nextBlobResults = blobsSegment.getContinuationToken();
for (ListBlobItem blobItem : blobsSegment.getResults()) {
if (blobItem instanceof CloudPageBlob) {
CloudPageBlob pageBlob = (CloudPageBlob) blobItem;
// TODO https://jira-hzn.eng.vmware.com/browse/VSYM-3445
try {
CloudBlob blobSnapshot = pageBlob.createSnapshot();
statsData.snapshots.add(blobSnapshot);
CloudPageBlob pageBlobSnapshot = (CloudPageBlob) blobSnapshot;
ArrayList<PageRange> pages = pageBlobSnapshot.downloadPageRanges();
// https://jira-hzn.eng.vmware.com/browse/VSYM-3355
for (PageRange pageRange : pages) {
statsData.utilizedBytes += pageRange.getEndOffset() - pageRange.getStartOffset();
}
} catch (StorageException e) {
logWarning(() -> String.format("Error getting blob size: [%s]", e.getMessage()));
}
}
}
} while (nextBlobResults != null);
}
} while (nextContainerResults != null);
} catch (Exception e) {
logWarning(() -> String.format("Exception while getting blob used bytes: %s", Utils.toString(e)));
exs.add(e);
} finally {
// in the Azure account
if (statsData.snapshots.size() > 0) {
synchronized (statsData.snapshots) {
Iterator<CloudBlob> snapshotIterator = statsData.snapshots.iterator();
while (snapshotIterator.hasNext()) {
try {
CloudBlob snapshot = snapshotIterator.next();
snapshot.deleteIfExists();
snapshotIterator.remove();
} catch (StorageException e) {
// Best effort to delete all the snapshots
logWarning(() -> String.format("Exception while deleting snapshot: %s", Utils.toString(e)));
}
}
}
}
}
// if all storage accounts were processed, create ServiceStat and finish
if (accountsCount.decrementAndGet() == 0) {
if (!exs.isEmpty()) {
handleError(statsData, exs.iterator().next());
return;
}
if (statsData.utilizedBytes != 0) {
ServiceStats.ServiceStat stat = new ServiceStats.ServiceStat();
stat.latestValue = statsData.utilizedBytes;
stat.sourceTimeMicrosUtc = TimeUnit.MILLISECONDS.toMicros(Utils.getNowMicrosUtc());
stat.unit = PhotonModelConstants.getUnitForMetric(metricName);
statDatapoints.add(stat);
}
statsData.statsResponse.statValues.put(metricName, statDatapoints);
if (statsData.statsResponse.statValues.size() == 1) {
statsData.statsResponse.computeLink = statsData.computeHostDesc.documentSelfLink;
}
statsData.stage = next;
handleStorageMetricDiscovery(statsData);
}
}
});
}
};
PhotonModelUtils.runInExecutor(this.executorService, getBlobsAsync, throwable -> handleError(statsData, throwable));
}
Aggregations