A few months back, the Azure team announced a new service offering, known as Azure Functions, which we are going to see in this article.
Introduction to Azure Functions
Before understating Azure Functions, let’s first understand the concept of ‘Event driven programming’. It is exactly what it sounds like: In a nutshell, it is writing a piece of code which will be executed whenever any particular event occurs.
As a quick example, folks who have worked on SharePoint technologies or with server object model can relate it very easily to the concept of the SP event receivers where, whenever an item is added, updated, or deleted in any SharePoint list, you have Item Added, Adding, Updated, Updating or Deleted, or Deleting events to respond to.
Similarly, Azure Functions is the experience where you will write a piece of code which will be responding to the events originated either from Azure or from other external sources, and the code itself will be executed on the Cloud. Sounds like a game changer! Doesn't it?
But wait. If you have ever worked with Clouds other than Azure, then you will know that this has been done with Amazon, where they call it AWS lambda. Google Cloud has something similar, too, known as Google Cloud Functions.
This whole idea basically revolves around the key concept of ‘Serverless Computing;' i.e., your piece of code responding to events and running on the Cloud does not need to worry about the infrastructure, giving you as a developer freedom to concentrate on your application logic rather than worrying about infrastructure maintenance, scalability, and deployments.
Azure Functions runtime
For the developer community, the next question could be: "Dude, if my code is going to be executed on the Cloud and you are telling me I should not worry about the infrastructure, then how does Azure know what runtime is required there?" Definitely, a great question. And, the answer to this is Azure Functions runtime.
Similar to .NET runtime, which is responsible for making everything available to run any .NET program, there is Azure Functions runtime which takes care of executing your code. As of writing this article, you are allowed to write your code in C#, Node.js, PowerShell, Python or PHP.
Note that Azure Functions runtime is open sourced and is available on
github.
Magic Infrastructure
All right! Now, we know what runtime is, but tell me where exactly Azure will execute this function code? It will, obviously, need some infrastructure to execute the code. Right? Yes, absolutely.
Do you remember Azure web apps? If yes, then we have a concept of Azure web jobs which runs within the context of web apps which, in-turn, is dependent on app service plans where we can define the size of the required infrastructure. Azure Functions are nothing but an extension to Azure web jobs, meaning that Azure Functions is based on web jobs SDK. With this knowledge, probably, now you know where the infrastructure requirements are catered from and how scalability would have been handled.
Function dependencies
If I were to write down the trigger based code and run it in Azure, what about the dependencies which my code counts on? E.g.- I am a big fan of NuGet and mostly employ various NuGets while writing my code, then will I be able to run my Functions on Azure with all these dependencies? The answer is Yes. Azure Functions does support all your dependencies and you can bring in all your custom assemblies or NuGet which are required to run your functions.
Function security
You can secure your trigger-based functions using OAuth providers, such as Azure AD, Facebook, Google, Twitter, or Microsoft live accounts.
Significance
Now, we are talking! I have tried to explain everything in the simplest way, but how can I relate it to real-world scenarios?
How one would be using these offerings?
Well, Azure Functions is really a comprehensive solution to cater to your various needs such as integrating multiple systems together, especially in IoT scenarios, building micro-services, or even for scheduled background jobs.
Let’s take a hypothetical scenario using IoT and see how it can be implemented using Azure Functions.
Recently, In India, the traffic police department has taken a great initiative to monitor the highway traffic on Mumbai-Pune expressway using drones, which will report high speeding vehicles or ‘un-mannered’ drivers to them. If we were to consider this scenario and implement it using Azure Functions, this is how it would have looked like.
Drones with camera and speed analysis engines will be triggering HTTP requests to the Azure Functions with captured vehicle images and other metadata information required to be fed into the system.
Azure Function will be invoked once it receives the HTTP request. It will not only publish a mail alert to the control room as well as SMS alert to the nearest patrolling vehicle, but will also create entries of vehicles in table and blob storage for future reference.
Function Templates
Note that this example is just to illustrate the use of Azure Functions with IoT applications. I have not put a lot of effort in designing the best architecture for the above system and improvement to it is, of course, possible.
HTTP trigger is just one kind of trigger to which Azure Functions can respond. As I mentioned previously, Azure Functions can respond to any event triggered within Azure or from outside Azure. As of writing this article, there are lots of Azure Function templates available and some of those are,
- Blob trigger – triggered when blob is added in container.
- Event hub trigger – respond to events added in event hubs.
- Service Bus topic trigger – execute functions whenever message is added to service bus topic.
- Timer trigger – execute functions on scheduled basis.
With this knowledge, let’s jump into the action and begin by creating our first Azure function.
Note that in this example we will be building Azure function using Http trigger template so that we can trigger it manually.
The simplest way to get started is by going to the Azure functions web site; i.e., https://functions.azure.com, or you can create it using Azure portal.
This article uses a process of creating functions using Azure portal.
Let’s start by creating a brand new resource group by clicking on the create new resource group button. We will name it as ‘SampleAzureFunctions’ and creat it in the Southeast Asia region.
Once the resource group is created, let’s click on Add and search with ‘Function App’. Click on Function App option from the list and click create.
As mentioned earlier, azure functions are extensions to web jobs so it needs service name, aka app name, and app service plan along with storage account.
Let’s create a new app service plan with the name ‘AzureFunctionPlan’ and new storage account ‘sampleazurefunc:’
Click create and it will create all required infrastructure to run your azure functions.
Now let’s browse to the function app which got created in our resource group.
You will be presented with a nice welcoming UI which provides lots of quick options to create your functions. At the bottom left of screen, you will see the option of Function app settings. We will see details of it later in this article.
For now, let’s click on the New Function option on the left and create our first function by selecting template Http Trigger C#. You can observe that there are lots of other templates provided to get us started, e.g. Queue trigger, Git hub webbook etc.
Once you select the template, you will be asked to give a name to your function and select the level of authorization.
Level of authorization decides the way you are going to access this function. If you declare the authorization level as function then you will need to use the API key to access this function over Http.
API keys can be found in host secret files and level can be changed later once the function is created.
These keys will be included in a query string while accessing the function over URL e.g.:
https://{function_app_name}.azurewebsites.net/api/{function_name}?code=api_function/master_key
The difference in function key and master key is that function key can trigger non-disabled functions while master key can be used to trigger enabled as well as disabled functions. If you wish that your functions can be triggered by master key then you will need to change the authorization level to ‘Admin’.
You can check both function and master key in host.json file by browsing to path below,
- “D:\home\data\functions\secrets\
- {
- "masterKey": "lEq7rFskywC6xVK7tlj73OmpUefnsx9bnSBiT1lWVRgq/me4jepP3g==",
- "functionKey": "9NBnl5fES9ZjvSa12IyDG4OOs14eWRJIWT763rMiQIBwKZvEZA2qAA=="
- }
How to reach to that path is simple – open your web app in kudu i.e. open url below,
https://your_function_app_name.scm.azurewebsites.net/DebugConsole
And you will see the directory structure in browser, you can navigate to host.json file mentioned above.
If the secrets folder contains a JSON file with the same name as a function, the key property in that file can also be used to trigger the function, and this key will only work with the function it refers to.
Now once you click create, it will create the function for you and you should see a screen similar to this.
Note that, at the top, it shows how to access this function with URL over Http and on the left it shows various tabs to work with this function.
The code editor at center has implemented a version of Run method which will be invoked whenever any Http request will be triggered for this function.
You can modify this code as per your needs and hit save button. It will first compile the code and related message will be shown in logs windows below code editor.
Let’s understand the bindings of input in auto generated code.
It is taking two input arguments; i.e., HttpRequestMessage and TraceWriter. The trace writer is used to log the inline processing messages to the logs screen shown in the below code editor.
HttpRequestMessage is standard object, and the source code above is trying to extract the value of parameter with ‘name’. But from where did this name come into it? We will see that in a bit.
Let’s understand the bindings to the input first and for that we will need to navigate to the next tab from options available in left pane; i.e., Integrate.
You can observe that it is going to run with standard mode with request parameter name req. Note that name of request parameter should match exactly in the source code’s parameter name. Observe images above.
Currently this function is going to generate the standard Http response which is selected in outputs option in above image.
You can choose to change these bindings simply by clicking on options and you will be presented with various other available options like If I click on new output I will be shown a screen like this,
Which means I can directly decide what I need as output whenever this function is executed -- interesting isn’t it? Meaning, I can directly generate the document using this function and store it in Azure blob storage or create Azure table storage entry.
For now, let’s not modify the output option and continue with standard Http response.
Apart from this, if you are a big fan of JSON editing then there isan advanced editor option to manage your input output bindings. All you need to do is simply click on advanced editor option and you will be shown a tiny JSON which looks like this, you can choose to modify and save it.
Let’s go back to the develop tab and let’s take a closer look at the source code.
All it is doing is, extracting the value of input parameter name either from query string or from request body contents, meaning that we can pass parameters to this function either from query string or from request body.
Let’s modify the code quickly to print first and last name of the user. Note that first name is passed from the query string while last name is passed via request body.
To validate if what is written above is working correctly, Azure functions provide you a great option; i.e., you can run your code after saving it directly from within the portal.
There is an option to run it below the logs screen.
Observe that I have sent the value of LastName parameter and only it was returned as HttpResponse output.
Now to test how we can pass the value of FirstName parameter is easy, simply copy the function URL mentioned at the top and paste it in a new browser tab with FirstName as query string parameter.
https://sampleazurefunctionapp.azurewebsites.net/api/SampleHttpTriggered?
code=1pf48hsc2eatyir81oynidx6rzkx4rsfqo36spc8nuj1c3diqmg6traumm9w67ib7is8m2t9&FirstName=Bhushan
And here is the response,
Sounds simple right? Great!
Now for the management and monitoring part of this function.
Click on the manage tab, this provides you an interface to manage your Azure function. You can choose to disable or enable your function from here or even delete it.
Next tab is Monitor using which you can track the usage of your function in terms of successful requests, recent errors, invocation logs etc.
All the monitoring is done through the concept of Pulse. Pulse is the live event stream of your function and shows you its successes and failures.
Previously in this article, it was mentioned that you can bring in all your external dependencies in Azure functions and it also supports nuggets, let’s see from where I can do it.
If you have observed the few screenshots above, there is this link in Develop tab which says ‘view files’. If you click on it, you can see the source code files and required metadata of your Azure function.
You can add, upload, edit or delete your dependent assemblies using this editor and refer to those in the code.
Function and app settings
As mentioned earlier in this article, Azure functions are the extensions of the web jobs and run in the context of app services backed by an app service plan. Let’s take a closer look at settings which can be controlled.
Click on it to take a closer look.
As seen in the image above, there is almost everything we can control for function apps.
The option of continuous integration enables a continuous deployment scenario of your Azure functions and it can easily integrate with various options like VSTS, One drive, Github, Dropbox etc.
As mentioned in the security section of this article, you can configure authentication and authorization settings of your function app and multiple identity management providers, including Azure AD, which is available for integration.
Next is the CORS settings. CORS stands for cross origin resource sharing meaning that you can control invocation of your functions from the browser beyond domain boundaries.
API Metadata setting allows you to specify the swagger 2.0 metadata so that other applications can easily find your function and your function becomes easy to consume.
App setting configuration is almost similar to what you see in Azure Web App Configurations. You can specify the settings, like environmental variables, connection strings, framework version, platform etc.
Portal console and kudu options lets you interact with the API file system and provides access to advanced features, like uploading zips.
Advanced settings options is your gateway, using which you can configure your app service settings, like custom domains, scale settings, SSL etc.
Pricing
Azure Functions pricing depends upon code execution time and number of executions of your functions. Execution time is metered as GBs. Refer to this excellent
article to get detailed information for Azure Functions pricing. This is all about Azure Functions which can help you to get started. In the next article, we will be integrating Azure Functions with Azure Logic Apps.