Thursday, July 30, 2020

Need to build event-driven architecture in the Azure? Easy with Azure Event Grid and Azure function!


Building and supporting infrastructure in the large organization can be a challenging task due to automation of all deployment steps, for example, creating cloud environments for a department with a set of virtual machines that contain preinstalled software, utilities, services, etc, that may have their own dependencies like database and storage, connection to log analytics and other log services. Utilities and services may have external dependencies as well. Therefore you need to have a mechanism to check and ensure that required connections are established, dependencies are installed, proper automation runbook is triggered. The mechanism should alert the administrator on error, perform a backup.

To build this mechanism I will use following azure resources.

Event Grid is a key component that acts as a main event event processor and contains:

  • Topics are azure resources that represent components that generate events.
  • Subscriptions/endpoint is azure resource that handles the event.

The relation between publisher components, events, topic, and subscriber/endpoint is shown in a diagram below.

Image for post

Event grid contains:

  • Dead Letter Queue and retry policy — if message not able to reach the Endpoint, then you should also configure retry policy
  • Event filtering — the rule which allows the event grid to deliver specific event types to the endpoint point. For example: when new VM will be created in the topic container (resource group, subscription, etc), the event will be caught end delivered to the endpoint (Service buss queue, storage queue)
Image for post

Queue Storage Account

is being used as a main event storage. When the event will be generated via Event Grid the final destination will be a queue.

Azure Function

Functions used as microservice, that contains logic to validate required resources and connections. Each function may contain also a database for storing configuration or state management data.

After a rather high-level architecture description I will provide more details on it below.

Architecture

Image for post

As you have noticed an event grid is linked with a subscription listening on the events related to new virtual machine creation. It is necessary to add filtering here, otherwise, the event grid will generate messages whenever any resource is created in a subscription or in the target resource group. All events delivered are delivered in the storage queue. In my project I’m using three queues:

  • The main queue is a destination for all messages from the event grid.
  • Retry queue receives all messages which failed during the first steps of validation and were scheduled for future retry.
  • Succeeded queue is used for all successfully processed messages. In my project I used this queue for future statistics and reporting.

Also a storage account is linked to Azure Log Analytics to synchronize all logs and alerts, for example, if there are more messages in the retry queue more than expected then log analytics will log this as an error alert administrator.

The next component is the Azure function app contains several azure function with validation, message processing and logic to trigger runbook.

Validation Function is linked with the main event queue. When the event grid sends a message to the main queue the function is automatically triggered.

Retry Function is based on a timer trigger and will be run constantly to check failed messages which were intended to retry (in retry event queue).

API Function(HTTP trigger) is intended to trigger (re-run) the whole process from runbook, Admin UI, etc.

The whole functions workflow described below.

Image for post

Architecture code base

The function app is written on PowerShell (Powershell Class) and uses principles of OOP. This approach allows us to build modular well-supported code and add or remove function at any time.

Why did I opt for PowerShell and not c# or JavaScript? The main reason is that a solution based on PS can be supported not only by developers but also by cloud administrators and system engineers.

Azure function app

I’ve placed the solution into one azure function app container, based on consumption plan, so that it does not use much resource power, and on the other hand if more CPU power or memory is required it is possible to automatically scale it up.

Each function contains one run file that represents a function and bindings configuration file where function triggers can be set up. Solution also contains common classes (modules) with code which reused across functions and operation related to cloud resources, for example, the AutomationAccountManager module contains the function to trigger runbook, etc.

Image for post

Below you can see the codesmaple of the main ValidationFunction example.

As you can see I referenced Common modules in a file header, then added input bindings using param directive, therefore when new VM will be created and event data will be placed in the main queue, this function will be triggered and $QueueItem variable receives payload (Here the example of Event Grid payload) including information about VM.

Common classes/modules

  • Validation module contains logic for checking a database server connection, however you can place there other validation logic. First of all it checks parameters, converts password to secure string and builds PSCredential object then setup SimplySql module if it doesn’t exist (SimplySql contains logic to establish connection and perform queries to database)
  • Automation Account Manager is module that contains logic to trigger runbook, retrieves private IP of VM and of course can contain other logic related to an automation account, for example create runbook based on template, remove etc.
  • Configuration retrieves configuration options from local and main settings config files, also provides logic to switch between local configuration settings and prod/test environments. I will explain more about configuration in CI/CD Architecture and pipeline section below.
  • AuthorisationManager is a module that provides an access to the Azure resources. Based on Azure Managed Identities and uses OAuth2 protocol based on JWT tokens. Allows local development of the function app. To use this options, you need to obtain JWT token and add update the auth variable in the module. The MSI with AuthorisationManager will be explained in detail in CI/CD Architecture and pipeline section.
  • QueueManager represents azure storage accounts queues resource and contains operations to get queue messages, add/create messages.

CI/CD Architecture and pipeline

Before I starting with explaining CI/CD architecture and pipeline let’s cover Azure Managed Identity topic.

Managed identities

Managed Identities (MSI) is service which allows your applications or functions to get access to the other azure resources. MSI based on Principal Accounts and OAuth2. In my case I need receive access to storage queue from function app.

When MSI is enabled for your resource, Azure will create Service Principal in Active Directory associated with this resource, but this principal account does not have the permission so we need assign the permission explicitly. This is will be the last step of the pipeline.

When Principal is created and required permission is assigned, MSI will work based on OAuth2 token based algorithm. Before accessing the storage queue, functions app service principal, sends credentials info to receive JWT token from AAD. Eventually, function sends this token to ADD for validation before accessing the Queue Storage. The whole process can be found on a diagram below.

Image for post

The details of MSI is out of scope of this article however Here and here you can get additional information and examples on this topic.

There are two options how to implement this process in the function app based on powershell:

  1. Using profile.ps1 file contains few lines of code where function does this authentication. The drawback of this approach is this options not always works locally.
  2. Create your own class/module which implements MSI authentication process. You can see example below.

AuthenticationTokenManager performs an authentication using MSI and allows switch between local and “real” environment. For local development it requires JWT token. You can obtain it using this command az account get-access-token --resource 'https://resource.azure.net'.

CI Pipeline

Image for post

Pipeline setups all required infrastructure. First of all it creates Event Grid with topic and sets up container to observe a subscription/resource group (here you can find Event Grid sources) also it creates storage queue account with three queues for an event store. Last step of the code, configures event grid subscription filter for acting only when new VM appears:

az eventgrid event-subscription create \....--included-event-types Microsoft.Resources.ResourceWriteSuccess \--advanced-filter data.operationName StringContains 'Microsoft.Compute/virtualMachines/write'

You can also chose Azure Service Bus instead of Storage Queue, if you need advanced and more performant event storage, which supports transactions, filtering, event-forwarding, dead letter queue, topics (here the list of all advanced service bus features).

Next step is to deploy function app as a resource and enable Managed Identities (MSI).

"identity": {    "type": "SystemAssigned"},

This includes deployments of storage account, required for storing project files and application logs.

After that we need to read secrets from key-vault, which is considered to be the best practice to store and retrieve secretes like master database account, storage and VMs passwords, etc., however we will skip step in the example.

Last steps is to compress (zip) function’s files source and to deploy an archive into the function app container, which we’ve created previously.

Here you can find already configured pipeline which can be imported into your Azure DevOps project.

Improvements

  • For the retry function I’m using Timer Function where I’m configuring polling interval based on Cron job format (0 */5 * * * *each 5 min) It can be replaced with Queue Trigger function with retry policy or Trigger Poling. An example of configuration is below:
{
"version": "2.0",
"extensions": {
"queues": {
"maxPollingInterval": "00:05:00",
"visibilityTimeout" : "00:00:60",
"batchSize": 16,
"maxDequeueCount": 3,
"newBatchThreshold": 5
}
}
}
  • Profile vs Authorization Module. Instead of using authorization module you can use profile.ps1 and authentication script section
....
if ($env:MSI_SECRET -and (Get-Module -ListAvailable Az.Accounts)) {
Connect-AzAccount -Identity}
....

However this option may not work in the local environment and you should configure MSI environment variables.

  • Add azure function proxies to modify URL format

Conclusion

In this article I described how to build event driven architecture to manage the virtual machine, related utilities and components.

The presented solution can be reused in following scenarios:

  • Key Vaults and SSL certificate management (check certificate expiration time, log and inform, update certificate automatically)
  • Create custom logic to build cloud expense reports
  • Cloud resources backup, check availability and log (using Log Analytics or other tools)
  • Resource clean up management
  • Container management solution

Source code

Power BI: Top 5 no-code AI & machine learning features

 

With 850,000 active users and more than 30 million dashboards and reports hosted, Power BI has fast become one of the most versatile self-service business intelligence tools for no-code data analysis.

Microsoft has consistently enhanced Power BI’s user-friendly capabilities in 2019, and one huge area of improvement that enterprises need to start taking advantage of is the rapid introduction of artificial intelligence (AI) capabilities in Power BI's dashboards and reports, which are key to unlocking deeper, previously unseen insights from our data.

Since the introduction of image and text analytics in March and AI services integration in June, Power BI users have been able to leverage the latest low-code conversational AI, natural language processing and voice recognition features for their own business data and extract greater actionable insights - all without having to be experts in the data science behind it all. Combined with scalable compute and more sophisticated data modelling, AI is no longer an inaccessible tool for regular analysts - it's already here,

We have rounded-up the top 5 best AI capabilities in Power BI that you need to start leveraging in your data analysis. Keep this page bookmarked as we update the list with Power BI's latest capabilities.


#1 - Power BI Q&A: Natural Language Processing

Image source: Microsoft

Data is more interesting to explore - and fun -  when it’s interactive and responsive.

By leveraging natural language processing (NLP), Power BI’s Q&A feature offers new ways to explore data and find hidden insights - and has received tons of fresh updates.

Power BI Q&A lets regular business users explore their datasets by asking specific questions, and responding with the best and most relevant answers, fully visualised. It also displays suggestions to help you form your question, and each visualisation changes dynamically as you modify the question. You can even set how Q&A displays answers; for example, asking to ‘show monthly performance as a graph’; this lets your users drill down into the results their way.

Power BI’s NLP capabilities have continued to evolve since its release. It recently enabled the in-built Q&A feature to be trained like a machine learning model, adapting to and understanding company-specific language and phrases to provide users with relevant results more intuitively. Report authors can also now view every single natural-language query asked by users so they can fine-tune how Power BI responds next time, improving its accuracy and responsiveness.

Perhaps in response to Tableau’s popular Ask Data feature set, Power BI’s natural language query and existing visual and text analysis components will be newly bolstered with updates that introduce better text and handwriting recognition, and entity detection. With these improvements, it’s easily one of the most polished NLP business intelligence services on the market across all of its different versions: Power BI Desktop, Power BI Pro and Power BI Premium.

It's important to note that Power BI Q&A only provides results about the data in Power BI, so it's only as extensive in capability as the data that is provided. Currently, only natural language queries asked in English are supported, but there are other languages such as Spanish currently in preview.

Version Availability: Power BI Q&A is available with a Power BI Pro or Premium licenses only.

 

#2 - Siri voice integration with Power BI Mobile: Conversational AI

 

Power BI offers on-the-go versions of its analytics reporting via a set of mobile applications for Android, iOS and Windows 10 smartphones and tablets - even Apple Watch.

On mobile, users can connect to and consume predefined dashboards and reports created in Power BI Desktop and on-premises reports on Power BI Report Server easily.

However, Power BI iOS mobile users are extra lucky and at the moment have exclusive access to two nifty conversational AI capabilities built into the app.

For starters, you can now add Siri shortcuts to frequently viewed dashboards and reports, enabling faster, seamless access to important items. You can set and use a specific voice command of your choice to immediately view and consume the data you want to explore, without sifting through the lists.

Power BI iOS users can also ask specific questions about their data and gain new insights and suggestions using the Q&A virtual analyst. The unique chat feature is in-built and tailor-made for mobile. The natural language querying is accessed via the action menu in each dashboard, where you can either type your question in the chat, or use iOS native speech recognition (voice) to ask questions.

For example:

  • While viewing a retail sales analysis report, you can ask Power BI Q&A to specifically filter last year’s sales against current performance and visualise it in a bar chart optimised for the smaller screens of your smartphone or tablet.
  • You can also use your voice via your mobile device’s microphone to ask Power BI to visualise the number of sales made in a given month in a column chart for a more detailed exploration - and for a more immediate answer.

The Power BI mobile Q&A virtual analyst is still evolving and the Siri integration is fresh out of this year’s Microsoft Business Application Summit, but both are great features and steps towards integrated AI capabilities that definitely should be leveraged by all Power BI users.

Version Availability: Siri voice integration and Q&A virtual analyst are only available on Power BI Mobile iOS app for iPad, iPhone and iPod Touch with iOS 10 or later.


#3 - Azure Cognitive Services integration: Machine Learning (ML)

natural_language_data_disruptor_2019

 

Azure Cognitive Services (ACS) is now integrated with Power BI Premium, opening up the door for users to leverage pre-trained machine learning models for greater insights. 

With ACS (no subscription required), business-level Power BI users can apply different ML algorithms to enrich their data during the self-service data preparation for data flows, which is the process of ingesting, cleansing, transforming, integrating and curating data from numerous sources in the business

Power BI now stores these ACS and ML-enhanced data flows in Azure Data Lake Storage, providing broader access to data engineers and data scientists throughout your organisation to leverage more advanced tools like Azure Databricks, Azure Machine Learning and Azure SQL Data Warehouse and apply additional advanced analytics and AI-driven capabilities to datasets.

Currently, there are four intelligent pre-trained models we can apply in Power BI to our text-based and image-based datasets:

  • Language detection
  • Key phrase extraction
  • Image tagging
  • Sentiment scoring.

Users can now use these machine learning models within Power BI  (and the AI Insights Browser in Power Query Online) to extract insights, for example from images by detecting relevant objects, or analyse text fields like customer feedback to pinpoint important phrases and positive comments for future analysis, or compare sentiment in different languages. All of these AI-powered benefits come back to our end-users who consume Power BI reports the most.

Version Availability: Azure Cognitive Services integration is available with a Power BI Premium licenses only.

 

 

# 4 - Power BI Key Influencers Visual: AI-powered visualisation

Key Influencers Visual - Top 5 AI features in Power BI

Image source: Microsoft

The Key Influencers Visual is a handy visualisation option in Power BI that helps users understand the factors that drive metrics (categorical and numerical) they’re most interested in, and how groups of key influential factors affect the selected condition. It’s fully interactive, and you can explore data using slicers, filters and other visualisations to represent the results.

Using a Key Influencers Visual to analyse your data sets means you can identify and contrast the relative importance of influential factors, and which have the most relevance. It’s entirely AI-powered, with intelligence built-in that runs behind the scenes to help users find new insights.

Power BI’s native integration with Azure Data Services means users can actively leverage substantial AI capabilities like machine learning to run regression analysis to model the influencer data and segmentation of the data overall - just by using the Key Influencers Visual.

While the public preview feature is still evolving and limited by a lack of consumption support for Power BI Embedded or Power BI Mobile and no support for metrics that are aggregate and measures, Microsoft have recently announced they are releasing two new companion AI visuals, Distribution Changes and Decomposition Tree, that further bolster Power BI.

  • Distribution Change: Will analyse what makes a distribution look different.
  • Decomposition Tree: Will enable users to drill into any dimension to further understand what influencers drive a key metric in question.

Ultimately, Power BI receiving more AI-enhanced visuals is only a great thing for deeper exploration and delivering previously unseen insights for both data analysts and business users.

Version Availability: Key Influencers Visual is available with a Power BI Premium or Pro licenses only.

 

# 5 - Advanced AI modelling with Azure Machine Learning

 

Azure Machine Learning (AML) is a low-code toolset that enables users to build entire data models, machine learning algorithms, pre-processing modules and more components through drag and drop gestures on an interactive design surface. You can run training experiments, examine results, link them together graphically and then deploy them to services like Power BI.

The latest Azure ML and Power BI integration empowers data scientists to more easily export their customised ML training models directly to Power BI (Premium only), helping business users take better advantage of the automated machine learning (AutoML) feature, which:

  • Enables business analysts using Power BI to use their dataflows and choose the best model to drive desired outcomes
  • Train their model on their data within Power BI and without needing to code anything
  • Automated reporting on its performance using Power BI’s dashboard and visualisations.

AutoML then allows users to evaluate and customise their best ML models until they are optimised, and then apply them to future datasets for predictive insights.

The best part? Most of the advanced data science aspects of ML modelling is automated and managed by Power BI, meaning both advanced data scientists and non-technical users can explore and benefit from AutoML’s capabilities - which continue to improve with regular updates.

As of June 2019, models created in Power BI can also be exported to Azure ML.

Version Availability: Azure Machine Learning integration is available with a Power BI Premium or Pro licenses only.

 

Conclusion

The key to taking advantage of Power BI's expansive and evolving AI and machine learning capabilities is a strong foundational business intelligence strategy. Before you begin exploring Power BI's many features, read our free-to-download BI whitepaper for a step-by-step guide on how to deliver better insights from your analytics.

Free hosting web sites and features -2024

  Interesting  summary about hosting and their offers. I still host my web site https://talash.azurewebsites.net with zero cost on Azure as ...