Thursday, 18 July 2019

Azure Functions Runtime is unreachable. Click here for details on storage configuration.


Azure Functions Runtime is unreachable. Click here for details on storage configuration.


Issue:

·       Azure Functions Runtime is unreachable.

·       Not able to do anything with this function.
·       Functions are not visible

Solution:

A very common issue which we face in Azure functions is,

Azure Functions Runtime is unreachable



Azure Functions Runtime is unreachable. Click here for details on storage configuration.


This exception is mostly related to Storage account. Either your storage account is not accessible, or credential are invalid, or storage account deleted.

When You see these types of issue, Your first troubleshooting step should be collecting the network trace immediately.
Please follow below steps to collect the network traces,
       Hit F12 on your browser
       Refresh browser (F5) - This will clear session caches
       Reproduce the issue.
       Export network trace as HAR file (Save all as HAR on Chrome/Edge/IE)

Once you have network trace then you can open it through Fiddler which will definitely give some information about some of the API failure.





While investigating this API failure I observed lot of messages related to Network.
You can click on any of the API failure (red color)  and click on preview (right side.)



As the message says something about Network, I quickly verified the network setting but I was getting this issue in other networks also that means this issue is not pertaining to the network.
  
I then checked Storage Account for this function. You can get the information about storage account from your application setting and refer either AzureWebJobsStorageor WEBSITE_CONTENTAZUREFILECONNECTIONSTRING




I further checked and confirmed unavailability of storage account. 

 Somehow my storage account was deleted by someone which was causing that issue. I created a new function app and was able to add a new function successfully.
So whenever you face this issue please check the network trace and storage account availability.

There might be other reason also. If your storage account is not deleted then you can check,
  • Are you able to tcpping your storage account form function app KUDU?
  • Do you have any firewall setting at storage account side which is preventing your function to connect with storage account.
  • Please check storage account connection string properly in your function app Application Setting section. And if possible get the storage account connection setting again and replace.

I believe this helps. Please share your feedback.


Tuesday, 16 July 2019

Azure Functions: The Consumption pricing tier is not allowed in this resource group


Azure Functions: The Consumption pricing tier is not allowed in this resource group


Issue:

·       The Consumption pricing tier is not allowed in this resource group

·       Dynamic pricing tier is not allowed in this resource group


Solution:

You may face this exception while creating the Azure functions in an existing resource group.


The Consumption pricing tier is not allowed in this resource group


The most important reason of this issue is “Scale Unit”.
Scale units are the underlying hardware and software that Microsoft manages, that Azure web apps runs on top off.

The fact that it doesn't always work in an existing Resource Group is a known limitation since Functions are not enabled in all scale units.
Eventually, all scale units will support Dynamic aka Consumption, and this condition will no longer be there.

Until then you can,
·       Create a new Resource Group.
·       Move your resource to other resource group where Consumption plan is supported.
·       Wait for consumption plan to be available in all scale units.



References:


I hope this helps.  Please share your feedback






Azure Functions | Unable to retrieve Functions keys | The function runtime is unable to start |Function host is not running | We are not able to retrieve the keys for function


Azure Functions | Unable to retrieve Functions keys |  The function runtime is unable to start | Function host is not running


Issue:
You might face one of the following exceptions while working with Azure functions.

·       Unable to retrieve Functions Keys

·       We are not able to retrieve the keys for function

·       The function runtime is unable to start. 

·       Function host is not running.

·       Internal Server error.

·       Service Unavailable.


Analysis:

When you create an Azure functions then few keys are created with it.
You can check those keys in “Function app Settings” section. 
Same keys can also be checked in the managed section.

We are not able to retrieve the keys for function


These keys are known as authorization keys. Refer below URL for more info


The most probable root cause of these exception is, “MISSING HOST KEYS”.

You can check below screen shot where I deleted the host keys and I started getting these exception messages.



These messages indicate REST API failure which retrieve host keys.


Solution:

The quickest way to resolve this issue is to RESET/CREATE these keys.
·       Go to KUDU https://<yourapp>.scm.AzureWebsites.net
·       Debug Console-> CMD.
·       Go to the secret keys path d:\home\data\functions\secrets
·       Download host.json file for backup and delete host.json file
·       Go to Process Explorer from top menu
·       Right click on the w3wp.exe process -> Kill

We are not able to retrieve the keys for function

·       RESTART your function app.
·       This action will create host.json and will create new keys.

Now, when you will open your function app again, you will observe that those keys are created, and exception message is disappeared.

We are not able to retrieve the keys for function

   Hope this helps. Please share your feedback.



Sunday, 14 July 2019

Azure | How to disable functions in Azure Functions


How to disable functions in Azure Functions


Disabling A Single Function in Azure Functions Deployed From Visual Studio

Issue:
·       You have one Precompiled (developed through Visual Studio) Azure function app.
·       You disabled it through Portal Manually
·       Even after disabling that function it is triggering.

Solution:

It is very easy to disable function if you create it through portal. You can simply set

 "disabled": true

in function.json file.

You face challenge when it is Precompiled function (which you developed through Visual Studio and appears as read only in portal).

You have to use “Disableattribute in the code.



The Disabled attribute is the only way to disable a class library function. The generated function.json file for a class library function is not meant to be edited directly. If you edit that file, whatever you do to the disabled property will have no effect.
The same goes for the Function state switch on the Manage tab, since it works by changing the function.json file.
Also, note that the portal may indicate the function is disabled when it isn't.

You can get more details in below URL,


References,



I believe this helps. Please share your feedback.

Thursday, 11 July 2019

Azure Function App Graceful Shutdown


Azure Function App Graceful Shutdown


Issue:
·       My function app is about to terminate, how can I notify my function code.
·       My function should not terminate unexpectedly.
·       How to detect host shutdown?
·       When my function app stop/restart then my code should notify and should be able to handle it.

Solution:

You can resolve these types of issue using “Cancellation Token”.

You can specify the CancellationToken parameter which will notify you code whenever function is going to terminate. You can use this notification to make sure the function doesn't terminate unexpectedly in a way that leaves data in an inconsistent state.


Ref:



Example code:

I created one HTTP Trigger function and passed CancellationToken

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Threading;

namespace FunGraceShut
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =>
            {
                log.LogInformation("Function app is stopping");               

            });
            string name = req.Query["name"];
            if (!cancellationToken.IsCancellationRequested)
            {
                for (int i = 0; i < 100; i++)
                {

                    log.LogInformation("C# HTTP trigger function processed a request.");
                    Thread.Sleep(8000);
                    log.LogInformation("Normal processing for queue message={0}", name);
                }

                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                name = name ?? data?.name;

                return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
                // the code to process the item goes here
            }
            return name != null
                    ? (ActionResult)new OkObjectResult($"Hello, {name}")
                    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
    }
}



You can refer below image when I stopped it while it was running.


Function App Graceful Shutdown

Ref:




Hope this helps. Please share your feedback.


Wednesday, 10 July 2019

Azure App Service : Automate Start/Stop/Restart web app


Azure App Service : Automate Start/Stop/Restart web app



Start/Stop/Restart web app through code/program 


Issue:
·       I want to stop/start/Restart my web app through code.
·       I want to restart my web app everyday at some certain time.
·       How can I automate it?

Solution:
A common ask from may app services users is, Is there any way to stop/start or restart web app programmatically. Once we have logic and program then we can simply automate that also.

Good news is you can write code to perform this operation. I am explaining this using PowerShell, but same approach can be used with other languages like C#.

Points to remember,
·       When we Stop, Start or Restart the web app from Portal, we internally call the REST API.
·       If we can call those REST API or http endpoint programmatically then our purposed can be fulfilled.

But the challenge is, you can’t simply call those REST API. You must pass authentication information also with the request. This authentication information can be username/password or Bearer token.
It is not the good practice to hardcode username/password in the code hence we should generate BEARER token at run time and will pass that.

We can use the concept of “Service Principal” to generate bearer token.
Please refer below URL to create service principal,

Once we have Application ID and Client secret then we can use following Power Shell command to automate this process.


$Auth = Invoke-RestMethod -Uri "https://login.microsoftonline.com/<Your Tenant ID>/oauth2/token?api-version=1.0" -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "<Your Application ID>"; "client_secret" = "<Your Client Secret ID>”}

$HeaderValue = "Bearer " + $Auth.access_token

#Stop
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/stop?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  

#Start
Invoke-RestMethod -Uri "https://management.azure.com/subscriptions/<your subscription id>/resourceGroups/<your resource group name>/providers/Microsoft.Web/sites/<your web app name>/start?api-version=2018-02-01" -Method Post -Headers @{Authorization = $HeaderValue}  



Please replace values according to your web app and configuration. (highlighted in yellow). Please modify this script according to your requirement.

You can get the list of other REST API in resource explorer feature of your web app.
Ref: 

You can use this script in your web job or function app or anywhere else to automate this process.

Hope this helps. Please share your feedback.

Azure Functions | Microsoft.Azure.WebJobs.Script.WebHost: Repository has more than 10 non-decryptable secrets backups

Microsoft.Azure.WebJobs.Script.WebHost: Repository has more than 10 non-decryptable secrets backups Issue : ·        The function runtime is...