storage account - export blob size and date [duplicate] - azure

I want to create an Azure function that deletes files from azure blob storage when last modifed older than 30 days.
Can anyone help or have a documentation to do that?

Assuming your storage account's type is either General Purpose v2 (GPv2) or Blob Storage, you actually don't have to do anything by yourself. Azure Storage can do this for you.
You'll use Blob Lifecycle Management and define a policy there to delete blobs if they are older than 30 days and Azure Storage will take care of deletion for you.
You can learn more about it here: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-lifecycle-management-concepts.

You can create a Timer Trigger function, fetch the list of items from the Blob Container and delete the files which does not match your criteria of last modified date.
Create a Timer Trigger function.
Fetch the list of blobs using CloudBlobContainer.
Cast the blob items to proper type and check LastModified property.
Delete the blob which doesn't match criteria.
I hope that answers the question.

I have used HTTP as the trigger as you didn't specify one and it's easier to test but the logic would be the same for a Timer trigger etc. Also assumed C#:
[FunctionName("HttpTriggeredFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[Blob("sandbox", Connection = "StorageConnectionString")] CloudBlobContainer container,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// Get a list of all blobs in your container
BlobResultSegment result = await container.ListBlobsSegmentedAsync(null);
// Iterate each blob
foreach (IListBlobItem item in result.Results)
{
// cast item to CloudBlockBlob to enable access to .Properties
CloudBlockBlob blob = (CloudBlockBlob)item;
// Calculate when LastModified is compared to today
TimeSpan? diff = DateTime.Today - blob.Properties.LastModified;
if (diff?.Days > 30)
{
// Delete as necessary
await blob.DeleteAsync();
}
}
return new OkObjectResult(null);
}
Edit - How to download JSON file and deserialize to object using Newtonsoft.Json:
public class MyClass
{
public string Name { get; set; }
}
var json = await blob.DownloadTextAsync();
var myClass = JsonConvert.DeserializeObject<MyClass>(json);

Related

Make Azure function blob binding case-insensitive

I have a C# Azure HTTPTrigger Function which will get a file from my blob storage.
This is a public REST method. The caller sends a string, which can be in any case.
Because the files are stored case sensitive, I'm not using a direct Blob binding but use the more generic binding, convert the input to upper-case and create a new Blob binding to get the blob stream:
public async Task<IActionResult> GetFile(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "file/{name}")] HttpRequest req,
IBinder binder, ExecutionContext context, string name)
{
// The file name is always upper-case:
var nameUpper = name.ToUpperInvariant();
// Get the file (the file has no extension), using the IBinder parameter instead of the [Blob()] parameter because we need to make name upper-case:
var blobStream = await binder.BindAsync<byte[]>(new BlobAttribute($"%BlobContainerName%/{nameUpper}", FileAccess.Read),
req.HttpContext.RequestAborted).ConfigureAwait(false);
Is this the most optimal way? Or can this be made simpler/easier?
It feels a bit hacky.

Azure BlobTrigger is firing > 5 times for each new blob

The following trigger removes exif data from blobs (which are images) after they are uploaded to azure storage. The problem is that the blob trigger fires at least 5 times for each blob.
In the trigger the blob is updated by writing a new stream of data to it. I had assumed that blob receipts would prevent further firing of the blob trigger against this blob.
[FunctionName("ExifDataPurge")]
public async System.Threading.Tasks.Task RunAsync(
[BlobTrigger("container/{name}.{extension}", Connection = "")]CloudBlockBlob image,
string name,
string extension,
string blobTrigger,
ILogger log)
{
log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name}");
try
{
var memoryStream = new MemoryStream();
await image.DownloadToStreamAsync(memoryStream);
memoryStream.Position = 0;
using (Image largeImage = Image.Load(memoryStream))
{
if (largeImage.Metadata.ExifProfile != null)
{
//strip the exif data from the image.
for (int i = 0; i < largeImage.Metadata.ExifProfile.Values.Count; i++)
{
largeImage.Metadata.ExifProfile.RemoveValue(largeImage.Metadata.ExifProfile.Values[i].Tag);
}
var exifStrippedImage = new MemoryStream();
largeImage.Save(exifStrippedImage, new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder());
exifStrippedImage.Position = 0;
await image.UploadFromStreamAsync(exifStrippedImage);
}
}
}
catch (UnknownImageFormatException unknownImageFormatException)
{
log.LogInformation($"Blob is not a valid Image : {name}.{extension}");
}
}
Triggers are handled in such a way that they track which blobs have been processed by storing receipts in container azure-webjobs-hosts. Any blob not having a receipt, or an old receipt (based on blob ETag) will be processed (or reprocessed).
since you are calling await image.UploadFromStreamAsync(exifStrippedImage); it gets triggered (assuming its not been processed)
When you call await image.UploadFromStreamAsync(exifStrippedImage);, it will update blob so the blob function will trigger again.
You can try to check the existing CacheControl property on the blob to not update it if it has been updated to break the loop.
// Set the CacheControl property to expire in 1 hour (3600 seconds)
blob.Properties.CacheControl = "max-age=3600";
So I've addressed this by storing a Status in metadata against the blob as it's processed.
https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-container-properties-metadata
The trigger then contains a guard to check for the metadata.
if (image.Metadata.ContainsKey("Status") && image.Metadata["Status"] == "Processed")
{
//an subsequent processing for the blob will enter this block.
log.LogInformation($"blob: {name} has already been processed");
}
else
{
//first time triggered for this blob
image.Metadata.Add("Status", "Processed");
await image.SetMetadataAsync();
}
The other answers pointed me in the right direction. I think it is more correct to use the metadata. Storing an ETag elsewhere seems redundant when we can store metadata. The use of "CacheControl" seems like too much of a hack, other developers might be confused as to what and why I have done it.

How to unit test azure functions blob storage trigger option?

I have an azure function which is triggered when a zip file is uploaded to an azure blob storage container. I unzip the file in memory and process the contents and add/update the result into a database. While for the db part I can use the in memory db option. Somehow am not too sure how to simulate the blob trigger for unit testing this azure function.
All the official samples and some blogs mostly talk about Http triggers(mocking httprequest) and queue triggers (using IAsynCollection).
[FunctionName("AzureBlobTrigger")]
public void Run([BlobTrigger("logprocessing/{name}", Connection = "AzureWebJobsStorage")]Stream blobStream, string name, ILogger log)
{
log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {blobStream.Length} Bytes");
//processing logic
}
There is a project about Unit test/ Integration test about azure function including blob trigger in github, please take a try at your side. Note that the unit test code is in FunctionApp.Tests folder.
Some code snippet about blob trigger from github:
unit test code of BlobFunction.cs
namespace FunctionApp.Tests
{
public class BlobFunction : FunctionTest
{
[Fact]
public async Task BlobFunction_ValidStreamAndName()
{
Stream s = new MemoryStream();
using(StreamWriter sw = new StreamWriter(s))
{
await sw.WriteLineAsync("This is a test");
BlobTrigger.Run(s, "testBlob", log);
}
}
}
}

Delete files older than X number of days from Azure Blob Storage using Azure function

I want to create an Azure function that deletes files from azure blob storage when last modifed older than 30 days.
Can anyone help or have a documentation to do that?
Assuming your storage account's type is either General Purpose v2 (GPv2) or Blob Storage, you actually don't have to do anything by yourself. Azure Storage can do this for you.
You'll use Blob Lifecycle Management and define a policy there to delete blobs if they are older than 30 days and Azure Storage will take care of deletion for you.
You can learn more about it here: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-lifecycle-management-concepts.
You can create a Timer Trigger function, fetch the list of items from the Blob Container and delete the files which does not match your criteria of last modified date.
Create a Timer Trigger function.
Fetch the list of blobs using CloudBlobContainer.
Cast the blob items to proper type and check LastModified property.
Delete the blob which doesn't match criteria.
I hope that answers the question.
I have used HTTP as the trigger as you didn't specify one and it's easier to test but the logic would be the same for a Timer trigger etc. Also assumed C#:
[FunctionName("HttpTriggeredFunction")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
[Blob("sandbox", Connection = "StorageConnectionString")] CloudBlobContainer container,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
// Get a list of all blobs in your container
BlobResultSegment result = await container.ListBlobsSegmentedAsync(null);
// Iterate each blob
foreach (IListBlobItem item in result.Results)
{
// cast item to CloudBlockBlob to enable access to .Properties
CloudBlockBlob blob = (CloudBlockBlob)item;
// Calculate when LastModified is compared to today
TimeSpan? diff = DateTime.Today - blob.Properties.LastModified;
if (diff?.Days > 30)
{
// Delete as necessary
await blob.DeleteAsync();
}
}
return new OkObjectResult(null);
}
Edit - How to download JSON file and deserialize to object using Newtonsoft.Json:
public class MyClass
{
public string Name { get; set; }
}
var json = await blob.DownloadTextAsync();
var myClass = JsonConvert.DeserializeObject<MyClass>(json);

Azure function inserting but not updating cosmosDB

I have an azure function taking in messages from an Azure service bus queue and sending documents to cosmosDB. I'm using Azure functions 1.x:
public static class Function1
{
[FunctionName("Function1")]
public static void Run([ServiceBusTrigger("ServiceBusQueue", AccessRights.Manage, Connection = "ServiceBusQueueConnection")]BrokeredMessage current, [DocumentDB(
databaseName: "DBname",
collectionName: "Colname",
ConnectionStringSetting = "CosmosDBConnection")]out dynamic document, TraceWriter log)
{
document = current.GetBody<MyObject>();
log.Info($"C# ServiceBus queue triggered function processed the message and sent to cosmos");
}
}
This inserts to cosmos successfully, but when updating I get errors:
Microsoft.Azure.Documents.DocumentClintException: Entity with the specified id already exists in the system.
They key I'm trying to update on is the partition key of that collection.
I saw this question: Azure function C#: Create or replace document in cosmos db on HTTP request
But It seems like my usage is similar to the one in Matias Quarantas answer. Also he mentioned that using an out parameter causes an upsert on cosmos.
How can I create this "upsert" function, while still using azure function 1.x?
The binding does indeed do an Upsert operation.
I created this sample Function that takes an Http payload (JSON) and stores it in Cosmos DB as-is:
[FunctionName("Function1")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req,
[DocumentDB("MyDb", "MyCollection", ConnectionStringSetting = "MyCosmosConnectionString")] out dynamic document,
TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
dynamic data = req.Content.ReadAsAsync<object>().GetAwaiter().GetResult();
document = data;
return req.CreateResponse(HttpStatusCode.OK);
}
If I send a JSON payload to the Http endpoint, the output binding works as expected:
When I check the Data Explorer, I see:
If I send a second payload, this time, adding a property (same id):
The Data Explorer shows the document was updated, with the same Function code:
Can you add the full Exception/Error trace? Is your Service Bus Message including an "id"? Is your collection partitioned?
If your collection is partitioned and you are changing the value of the Partition key property, then the binding won't update the existing document, it will create a new one because the Upsert operation won't find an existing document (based on the id/partition key). But it won't throw an exception.

Resources