Detecting update/redeployment inside running Azure

2019-08-17 02:13发布

问题:

The WebJobs SDK supports passing in a CancellationToken argument to a function which is used by the SDK to notify running functions of a host shutdown. I have noticed though that running functions are not notified if the app/function is replaced by a new version. This is a problem if functions are designed to run for a longer period of time, since you could end up having "old" logic running without knowing it.

For example, if you create a simple function that will run forever (or until cancelled):

using System;
using System.Threading;

public static async Task Run(string input, TraceWriter log, CancellationToken token)
{
    while (!token.IsCancellationRequested) 
    {    
        token.ThrowIfCancellationRequested();
        log.Info($"Input: {input}");
        await Task.Delay(2000, token).ConfigureAwait(false);
    }
}

If you run that, and then update the code in some way and redeploy (or save, if you're in the Azure Functions portal), you'll see that the function is recompiled but the running function instance is not stopped and will continue executing the previous version of the code until you disable it manually.

Is there some way of detecting a redeployment inside a running function?

回答1:

Azure Functions does honor the WebJobs SDK CancellationToken model when the Function App host is shutting down/restarting. However, in the scenario above where you're simply updating the function code itself, that will not trigger a host restart, which is why the token isn't being cancelled. As an optimization, we only restart the host when absolutely necessary, and in the case of simple code updates we can keep the host running, and just use the new code on any new invocations.

That works well for normal Function scenarios where Function invocations don't live "forever". I'd say a while(true) function is an anti-pattern - Functions isn't designed for that type of thing, and you can likely accomplish your scenarios in a better way. On a related note, will also be putting some time limits (configurable) in place for Function executions before GA.