Search code examples
asp.netiisazureazure-web-roles

How to programmatically restart Application Pool when 503 occurs from Azure Web Role


If an Azure site's application pool shuts down due to Rapid Fail Protection is it possible to restart it again automatically?

This question asks pretty much the same question but not related to azure ASP.NET application pool shutdown problem

Possibly using a WebRole to monitor and some adaption of the code on this page Is it possible to restart IIS on a Azure web role without restarting the process?

var mgr = new ServerManager();
var azurePools = mgr.ApplicationPools.Where(p => Guid.TryParse(p.Name));
azurePools.ToList().ForEach(p => p.Recycle());

Solution

  • You can run the following script from a startup task (make sure you create an elevated background task):

    Timeout= 30000
    set events = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecNotificationQuery("select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent' and TargetInstance.LogFile='System' and TargetInstance.EventCode=5002") 
    Do
        WScript.Echo "==========================================================================="
        WScript.Echo "Listening for IIS Rapid Fail Protection Events"
        Set objLatestEvent = events.NextEvent
        Wscript.Echo objLatestEvent.TargetInstance.Message
        ' get the AppPool name from the Eventlog message
        appPool = objLatestEvent.TargetInstance.InsertionStrings(0)
        WScript.Echo "Restarting Application Pool '" & appPool & "' in " & Timeout & " milliseconds"
        WScript.Sleep(Timeout)
        'construct ADSI path to failed AppPool and start by setting AppPoolCommand to 1
        set pool = GetObject("IIS://localhost/w3svc/AppPools/" & appPool)
        pool.AppPoolCommand = 1
        pool.SetInfo
        WScript.Echo "AppPool " & appPool & " restarted"
        WScript.Echo "==========================================================================="
        WScript.Echo
    Loop
    

    Using WMI it will listen for IIS RFP events. This is done by combining ExecNotificationQuery with NextEvent. The call to NextEvent will block until a new event arrives. When this happens, the script waits 30sec and restarts the application pool.

    Anyways, if RFP kicks in it might be more appropriate to see why your process is crashing over and over again.